-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscratchpad.lua
More file actions
383 lines (333 loc) · 10.8 KB
/
Copy pathscratchpad.lua
File metadata and controls
383 lines (333 loc) · 10.8 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
-- Scratchpad Module for Hammerspoon
-- A simple textarea that syncs to iCloud with E2E encryption
--
-- To copy the encryption key to another Mac:
-- 1. Run: security find-generic-password -a "hammerspoon" -s "scratchpad-encryption-key" -w
-- 2. Copy the output
-- 3. On the other Mac, run:
-- security add-generic-password -a "hammerspoon" -s "scratchpad-encryption-key" -w "PASTE_KEY_HERE"
local M = {}
local htmlLoader = require("html_loader")
-- Private state
local webview = nil
local menubarItem = nil
local hotkey = nil
local config = {}
local isVisible = false
local isTransitioning = false
-- Keychain constants
local KEYCHAIN_ACCOUNT = "hammerspoon"
local KEYCHAIN_SERVICE = "scratchpad-encryption-key"
local function getEncryptionKey()
local cmd = string.format(
'security find-generic-password -a "%s" -s "%s" -w 2>/dev/null',
KEYCHAIN_ACCOUNT, KEYCHAIN_SERVICE
)
local output, status = hs.execute(cmd)
if status and output and #output > 0 then
return output:gsub("%s+$", "")
end
return nil
end
local function createEncryptionKey()
local genCmd = "openssl rand -base64 32"
local key, genStatus = hs.execute(genCmd)
if not genStatus or not key then
return nil, "Failed to generate key"
end
key = key:gsub("%s+$", "")
local storeCmd = string.format(
'security add-generic-password -a "%s" -s "%s" -w "%s"',
KEYCHAIN_ACCOUNT, KEYCHAIN_SERVICE, key
)
local _, storeStatus = hs.execute(storeCmd)
if not storeStatus then
return nil, "Failed to store key in Keychain"
end
return key
end
-- Encryption helpers
local function encrypt(plaintext, key)
local encoded = hs.base64.encode(plaintext)
local cmd = string.format(
'echo "%s" | base64 -d | openssl enc -aes-256-cbc -pbkdf2 -salt -pass pass:%s -base64',
encoded, key
)
local output, status = hs.execute(cmd)
if status and output then
return output:gsub("%s+$", "")
end
return nil
end
local function decrypt(ciphertext, key)
local cmd = string.format(
'echo "%s" | openssl enc -aes-256-cbc -pbkdf2 -d -pass pass:%s -base64 2>/dev/null',
ciphertext:gsub("%s+$", ""), key
)
local output, status = hs.execute(cmd)
if status and output then
return output
end
return nil
end
local function isEncrypted(content)
return content:match("^U2FsdGVk")
end
-- File I/O
local function ensureDirectory()
local dir = config.filePath:match("(.+)/[^/]+$")
hs.fs.mkdir(dir)
end
local function checkForConflicts()
local dir = config.filePath:match("(.+)/[^/]+$")
local basename = config.filePath:match("([^/]+)$"):match("(.+)%..+$") -- "scratchpad"
local conflicts = {}
for file in hs.fs.dir(dir) do
-- Match patterns like "scratchpad 2.txt", "scratchpad (1).txt"
if file:match("^" .. basename .. " %d+%.") or file:match("^" .. basename .. " %(") then
table.insert(conflicts, file)
end
end
if #conflicts > 0 then
hs.notify.new({
title = "Scratchpad",
informativeText = "iCloud conflict detected: " .. table.concat(conflicts, ", "),
withdrawAfter = 15
}):send()
return true
end
return false
end
local function readFile()
local f = io.open(config.filePath, "r")
if not f then
ensureDirectory()
f = io.open(config.filePath, "w")
if f then f:close() end
return ""
end
local content = f:read("*a")
f:close()
if not content or content == "" then
return ""
end
if isEncrypted(content) then
-- Encrypted file: MUST have key, error if missing
local key = getEncryptionKey()
if not key then
hs.notify.new({
title = "Scratchpad",
informativeText = "Encryption key not found in Keychain. Import the key first.",
withdrawAfter = 10
}):send()
return nil -- Signal error to caller
end
local decrypted = decrypt(content, key)
if decrypted then
return decrypted
else
hs.notify.new({
title = "Scratchpad",
informativeText = "Decryption failed - wrong key or corrupted file",
withdrawAfter = 5
}):send()
return nil
end
else
-- Plaintext file (migration): will be encrypted on save
return content
end
end
local function saveFile(content)
ensureDirectory()
-- Check if existing file is encrypted
local existingFile = io.open(config.filePath, "r")
local existingContent = existingFile and existingFile:read("*a") or ""
if existingFile then existingFile:close() end
local key = getEncryptionKey()
-- If encrypted file exists but no key, refuse to overwrite
if isEncrypted(existingContent) and not key then
hs.notify.new({
title = "Scratchpad",
informativeText = "Cannot save: encryption key not found. Import the key first.",
withdrawAfter = 10
}):send()
return false
end
-- Create key if needed (new file or plaintext migration)
if not key then
key = createEncryptionKey()
if not key then
hs.notify.new({
title = "Scratchpad",
informativeText = "Failed to create encryption key",
withdrawAfter = 5
}):send()
return false
end
end
local encrypted = encrypt(content or "", key)
if not encrypted then
hs.notify.new({
title = "Scratchpad",
informativeText = "Encryption failed",
withdrawAfter = 5
}):send()
return false
end
local f = io.open(config.filePath, "w")
if f then
f:write(encrypted)
f:close()
print("Scratchpad saved (encrypted)")
return true
end
print("Scratchpad: Failed to save file")
hs.notify.new({
title = "Scratchpad",
informativeText = "Failed to save - check iCloud folder permissions",
withdrawAfter = 5
}):send()
return false
end
-- HTML template
local function buildHTML(content)
-- "</" must become "<\/" so content containing "</script>" can't terminate the inlined script block
local escaped = content:gsub("\\", "\\\\"):gsub("`", "\\`"):gsub("${", "\\${"):gsub("</", "<\\/")
return htmlLoader.load("scratchpad", { ["{{CONTENT}}"] = escaped })
end
-- WebView management
-- Sentinel returned when the editor JS never initialized (e.g. CodeMirror CDN unreachable);
-- saving in that state would overwrite the file with empty content
local EDITOR_NOT_READY = "__SCRATCHPAD_EDITOR_NOT_READY__"
local GET_CONTENT_JS = "window.getEditorValue ? window.getEditorValue() : '" .. EDITOR_NOT_READY .. "'"
local function hideWebview()
if webview and isVisible then
webview:hide()
isVisible = false
print("Scratchpad hidden")
end
end
local function showWebview()
if not webview then
-- Create user content controller for JS -> Lua messages
local usercontent = hs.webview.usercontent.new("scratchpad")
:setCallback(function(msg)
if type(msg.body) == "table" then
saveFile(msg.body.content)
if msg.body.action == "save_and_close" then
hideWebview()
end
end
end)
-- Get screen dimensions for centering (use screen where mouse cursor is)
local screen = hs.mouse.getCurrentScreen():frame()
local width = 600
local height = 400
local rect = {
x = (screen.w - width) / 2,
y = (screen.h - height) / 2,
w = width,
h = height
}
webview = hs.webview.new(rect, { developerExtrasEnabled = false }, usercontent)
:allowTextEntry(true)
:windowStyle({"titled", "closable", "resizable"})
:windowTitle("Scratchpad")
:closeOnEscape(false) -- We handle Escape manually for saving
:windowCallback(function(action, wv, state)
if action == "closing" then
-- Save before hiding
webview:evaluateJavaScript(
GET_CONTENT_JS,
function(result, error)
if result and result ~= EDITOR_NOT_READY then saveFile(result) end
end
)
isVisible = false
end
end)
end
-- Reposition to cursor's screen each time
local screen = hs.mouse.getCurrentScreen():frame()
local width = 600
local height = 400
webview:frame({
x = screen.x + (screen.w - width) / 2,
y = screen.y + (screen.h - height) / 2,
w = width,
h = height
})
-- Check for iCloud conflicts
checkForConflicts()
-- Load current content
local content = readFile()
if content == nil then
-- Decryption failed, don't show webview
print("Scratchpad: cannot open - decryption failed")
return
end
webview:html(buildHTML(content))
webview:show()
webview:hswindow():focus()
isVisible = true
print("Scratchpad shown")
end
local function toggleWebview()
if isTransitioning then return end
if isVisible then
isTransitioning = true
if webview then
webview:evaluateJavaScript(
GET_CONTENT_JS,
function(result, error)
if result and result ~= EDITOR_NOT_READY then saveFile(result) end
hideWebview()
isTransitioning = false
end
)
else
hideWebview()
isTransitioning = false
end
else
showWebview()
end
end
-- Menu bar
local function buildMenu()
return {
{ title = "Show Scratchpad", fn = toggleWebview },
{ title = "-" },
{ title = "Open in Finder", fn = function()
local dir = config.filePath:match("(.+)/[^/]+$")
hs.open(dir)
end }
}
end
-- Public API
function M.init(cfg)
config.filePath = cfg.filePath or (os.getenv("HOME") .. "/Library/Mobile Documents/com~apple~CloudDocs/Scratchpad/scratchpad.txt")
config.hotkey = cfg.hotkey or { {"ctrl", "alt"}, "s" }
-- Hotkey
hotkey = hs.hotkey.bind(config.hotkey[1], config.hotkey[2], toggleWebview)
print("Scratchpad loaded (Ctrl+Option+S to toggle)")
return M
end
function M.stop()
if webview then
webview:delete()
webview = nil
end
if hotkey then
hotkey:delete()
hotkey = nil
end
isVisible = false
print("Scratchpad stopped")
end
-- Function for unified menu integration
function M.getMenuItems()
return buildMenu()
end
return M