-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-writer.ps1
More file actions
77 lines (67 loc) · 2.92 KB
/
file-writer.ps1
File metadata and controls
77 lines (67 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# file-writer.ps1
# Listens on localhost:9998 for POST { filename, content } and writes the file to disk.
# Used by n8n workflows that can't write files directly (Code node sandbox blocks fs).
#
# Usage:
# powershell -ExecutionPolicy Bypass -File file-writer.ps1
#
# To enable secret validation, set $Secret below to match fileWriterSecret in your Config node.
$Port = 9998
$Secret = "" # Leave empty to skip validation. Set to match fileWriterSecret in Config node.
$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add("http://localhost:$Port/")
$listener.Start()
Write-Host "file-writer listening on http://localhost:$Port/ (press Ctrl+C to stop)"
try {
while ($listener.IsListening) {
$context = $listener.GetContext()
$request = $context.Request
$response = $context.Response
try {
# Validate secret if configured
if ($Secret -ne "") {
$incoming = $request.Headers["X-Writer-Secret"]
if ($incoming -ne $Secret) {
$response.StatusCode = 401
$response.Close()
Write-Host "$(Get-Date -f 'HH:mm:ss') 401 Unauthorized (bad secret)"
continue
}
}
# Read body
$reader = [System.IO.StreamReader]::new($request.InputStream)
$body = $reader.ReadToEnd()
$reader.Close()
$payload = $body | ConvertFrom-Json
$filename = $payload.filename
$content = $payload.content
if (-not $filename -or -not $content) {
throw "Missing filename or content in request body"
}
# Create directory if needed and write file
$dir = Split-Path -Parent $filename
if ($dir -and -not (Test-Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
}
[System.IO.File]::WriteAllText($filename, $content, [System.Text.Encoding]::UTF8)
$response.StatusCode = 200
$bytes = [System.Text.Encoding]::UTF8.GetBytes('{"ok":true}')
$response.ContentType = "application/json"
$response.ContentLength64 = $bytes.Length
$response.OutputStream.Write($bytes, 0, $bytes.Length)
$response.Close()
Write-Host "$(Get-Date -f 'HH:mm:ss') 200 Written: $filename"
} catch {
$response.StatusCode = 500
$bytes = [System.Text.Encoding]::UTF8.GetBytes("{`"error`":`"$($_.Exception.Message)`"}")
$response.ContentType = "application/json"
$response.ContentLength64 = $bytes.Length
$response.OutputStream.Write($bytes, 0, $bytes.Length)
$response.Close()
Write-Host "$(Get-Date -f 'HH:mm:ss') 500 Error: $($_.Exception.Message)"
}
}
} finally {
$listener.Stop()
Write-Host "file-writer stopped."
}