568 lines
26 KiB
JavaScript
568 lines
26 KiB
JavaScript
ObjC.import('Cocoa')
|
|
ObjC.import('CoreGraphics')
|
|
ObjC.import('Foundation')
|
|
|
|
const none = 'none\t\t\t0'
|
|
const browserBundles = new Set([
|
|
'com.google.Chrome', 'com.google.Chrome.canary', 'org.chromium.Chromium',
|
|
'com.apple.Safari', 'com.apple.SafariTechnologyPreview', 'com.microsoft.edgemac',
|
|
'org.mozilla.firefox', 'company.thebrowser.Browser', 'com.brave.Browser',
|
|
'com.operasoftware.Opera', 'com.vivaldi.Vivaldi'
|
|
])
|
|
|
|
function contains(r, x, y) {
|
|
return x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height
|
|
}
|
|
|
|
function globalRect(frame, mainH) {
|
|
return {X: frame.origin.x, Y: mainH - frame.origin.y - frame.size.height,
|
|
Width: frame.size.width, Height: frame.size.height}
|
|
}
|
|
|
|
function hit(args) {
|
|
const [index, nx, ny] = args.slice(0, 3).map(v => v.trim() ? Number(v) : NaN)
|
|
const screens = $.NSScreen.screens
|
|
if (!Number.isInteger(index) || index < 0 || index >= screens.count ||
|
|
!Number.isFinite(nx) || !Number.isFinite(ny) || nx < 0 || nx > 1 || ny < 0 || ny > 1) return {}
|
|
const mainH = screens.objectAtIndex(0).frame.size.height
|
|
const screen = screens.objectAtIndex(index)
|
|
const frame = globalRect(screen.frame, mainH)
|
|
const x = frame.X + nx * (frame.Width - 1)
|
|
const y = frame.Y + ny * (frame.Height - 1)
|
|
const options = $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements
|
|
const rawList = $.CGWindowListCopyWindowInfo(options, 0)
|
|
const allWindows = rawList ? (ObjC.deepUnwrap(ObjC.castRefToObject(rawList)) || []) : []
|
|
const windows = allWindows.filter(w => w && w.kCGWindowBounds &&
|
|
w.kCGWindowLayer === 0 && w.kCGWindowAlpha > 0.01 &&
|
|
w.kCGWindowOwnerName !== 'Window Server' && w.kCGWindowBounds.Width > 1 &&
|
|
w.kCGWindowBounds.Height > 1)
|
|
const top = windows.find(w => contains(w.kCGWindowBounds, x, y))
|
|
return {top, windows, desktop: contains(globalRect(screen.visibleFrame, mainH), x, y)}
|
|
}
|
|
|
|
function resolve(args) {
|
|
try { return resolveTarget(args) } catch (_) { return none }
|
|
}
|
|
|
|
function resolveTarget(args) {
|
|
if (args[3] !== 'true') return none
|
|
const {top, desktop} = hit(args)
|
|
if (!top) {
|
|
const path = $.NSHomeDirectory().js + '/Desktop'
|
|
const dir = Ref()
|
|
const fm = $.NSFileManager.defaultManager
|
|
return desktop && fm.fileExistsAtPathIsDirectory(path, dir) && dir[0] && fm.isWritableFileAtPath(path)
|
|
? ['desktop', 'Desktop', path, '0'].join('\t') : none
|
|
}
|
|
const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID)
|
|
const id = app && app.bundleIdentifier ? app.bundleIdentifier.js : ''
|
|
const label = ((app && app.localizedName && app.localizedName.js) ||
|
|
top.kCGWindowOwnerName || id || 'App').replace(/[\t\r\n]/g, '')
|
|
return [id === 'com.apple.Photos' ? 'photos' : 'window', label, id, String(top.kCGWindowNumber || 0)].join('\t')
|
|
}
|
|
|
|
const stealthTypes = ['org.nspasteboard.TransientType', 'org.nspasteboard.AutoGeneratedType']
|
|
|
|
function addStealth(item) {
|
|
for (const type of stealthTypes)
|
|
if (!item.types.containsObject($(type)) && !item.setDataForType($.NSData.data, $(type))) throw Error('Cannot mark pasteboard item')
|
|
return item
|
|
}
|
|
|
|
function readImagePNG(path) {
|
|
if (!/\.(png|jpe?g|webp|gif|bmp|heic|tiff?)$/i.test(path)) return null
|
|
try {
|
|
const attrs = $.NSFileManager.defaultManager.attributesOfItemAtPathError(path, null)
|
|
if (attrs.fileType.js !== $.NSFileTypeRegular.js || !(Number(attrs.fileSize) <= 32 * 1024 * 1024)) return null
|
|
if (/\.png$/i.test(path)) {
|
|
const png = $.NSData.dataWithContentsOfFile(path)
|
|
return png && !png.isNil() ? png : null
|
|
}
|
|
const img = $.NSImage.alloc.initWithContentsOfFile(path)
|
|
const rep = $.NSBitmapImageRep.imageRepWithData(img.TIFFRepresentation)
|
|
const png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({}))
|
|
return png && !png.isNil() ? png : null
|
|
} catch (_) { return null }
|
|
}
|
|
|
|
function resolveCommandKey() {
|
|
const modifiers = [
|
|
[0x7000000E3, 'meta_l'], [0x7000000E7, 'meta_r'], [0x7000000E2, 'alt'],
|
|
[0x7000000E6, 'alt_r'], [0x7000000E0, 'ctrl'], [0x7000000E4, 'ctrl_r'],
|
|
[0x700000039, 'caps_lock'], [0x7000000E1, 'shift'], [0x7000000E5, 'shift_r'],
|
|
]
|
|
const map = new Map(modifiers.map(([usage]) => [usage, usage]))
|
|
function normUsage(v) {
|
|
if (typeof v !== 'number' && !(typeof v === 'string' && /^(?:0x[\da-f]+|\d+)$/i.test(v))) return NaN
|
|
const n = Number(v)
|
|
if (!Number.isSafeInteger(n)) return NaN
|
|
return n >= 0 && n < 0x10000 ? n + 0x700000000 : n
|
|
}
|
|
function apply(src, dst) {
|
|
src = normUsage(src)
|
|
dst = normUsage(dst)
|
|
if (map.has(src) && Number.isFinite(dst)) map.set(src, dst)
|
|
}
|
|
function preference(key) {
|
|
try {
|
|
const value = $.CFPreferencesCopyValue($(key), $.kCFPreferencesAnyApplication,
|
|
$.kCFPreferencesCurrentUser, $.kCFPreferencesCurrentHost)
|
|
const entries = value ? ObjC.deepUnwrap(ObjC.castRefToObject(value)) : null
|
|
if (Array.isArray(entries)) return entries
|
|
} catch (_) {}
|
|
return []
|
|
}
|
|
let entries = preference('com.apple.keyboard.modifiermapping.1575-1-0')
|
|
if (!entries.length) entries = preference('com.apple.keyboard.modifiermapping.0-0-0')
|
|
for (const entry of entries) {
|
|
if (entry) apply(entry.HIDKeyboardModifierMappingSrc, entry.HIDKeyboardModifierMappingDst)
|
|
}
|
|
try {
|
|
const task = $.NSTask.alloc.init
|
|
const pipe = $.NSPipe.pipe
|
|
task.launchPath = '/usr/bin/hidutil'
|
|
task.arguments = $(['property', '--get', 'UserKeyMapping'])
|
|
task.standardOutput = pipe
|
|
task.standardError = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.launch
|
|
const data = pipe.fileHandleForReading.readDataToEndOfFile
|
|
task.waitUntilExit
|
|
if (task.terminationStatus === 0) {
|
|
const output = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js
|
|
for (const block of output.match(/\{[^{}]*\}/g) || []) {
|
|
const src = /"?HIDKeyboardModifierMappingSrc"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block)
|
|
const dst = /"?HIDKeyboardModifierMappingDst"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block)
|
|
if (src && dst) apply(src[1], dst[1])
|
|
}
|
|
}
|
|
} catch (_) {}
|
|
for (const command of [0x7000000E3, 0x7000000E7]) {
|
|
for (const [usage, qcode] of modifiers) {
|
|
if (map.get(usage) === command) return qcode
|
|
}
|
|
}
|
|
return 'meta_l'
|
|
}
|
|
|
|
function requestPaste(url, id, activateClick, commandKey, focusWaitMs) {
|
|
if (!/^[A-Za-z0-9_-]+$/.test(id)) throw Error('Invalid drop ID')
|
|
const body = {drop_id: id}
|
|
if (activateClick) body.activate_click = true
|
|
if (commandKey && commandKey !== 'meta_l') body.command_key = commandKey
|
|
if (focusWaitMs > 0) body.focus_wait_ms = focusWaitMs
|
|
postToHost(url, body)
|
|
}
|
|
|
|
function postToHost(url, body) {
|
|
const rawTok = $.NSProcessInfo.processInfo.environment.objectForKey($('REIMS_TOKEN'))
|
|
const token = rawTok && !rawTok.isNil() ? rawTok.js : ''
|
|
if (!token || /[\r\n\0]/.test(url + token)) throw Error('Invalid paste request')
|
|
const config = ['url = ' + JSON.stringify(url), 'header = ' + JSON.stringify('Authorization: Bearer ' + token)]
|
|
if (body) config.push('header = "Content-Type: application/json"', 'data-raw = ' + JSON.stringify(JSON.stringify(body)))
|
|
const task = $.NSTask.alloc.init
|
|
const input = $.NSPipe.pipe
|
|
task.launchPath = '/usr/bin/curl'
|
|
task.arguments = $(['-fsS', '-m', '10', '-X', 'POST', '-K', '-'])
|
|
task.standardInput = input
|
|
task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.launch
|
|
try { input.fileHandleForWriting.writeData($(config.join('\n') + '\n').dataUsingEncoding($.NSUTF8StringEncoding)) }
|
|
finally { input.fileHandleForWriting.closeFile }
|
|
task.waitUntilExit
|
|
if (task.terminationStatus !== 0) throw Error('Paste request failed')
|
|
}
|
|
|
|
function savePasteboard(pb, allowMissing, stealthRestore) {
|
|
const originals = pb.pasteboardItems
|
|
const saved = []
|
|
if (!originals || originals.isNil()) return saved
|
|
for (let i = 0; i < originals.count; i++) {
|
|
const source = originals.objectAtIndex(i)
|
|
const copy = $.NSPasteboardItem.alloc.init
|
|
const types = source.types
|
|
for (let j = 0; j < types.count; j++) {
|
|
const type = types.objectAtIndex(j)
|
|
if (stealthRestore && stealthTypes.includes(type.js)) continue
|
|
try {
|
|
const data = source.dataForType(type)
|
|
if (!data || data.isNil() || !copy.setDataForType(data, type))
|
|
throw Error('Cannot save pasteboard flavor ' + type.js)
|
|
} catch (err) {
|
|
if (!allowMissing) throw err
|
|
}
|
|
}
|
|
if (copy.types.count) saved.push(stealthRestore ? addStealth(copy) : copy)
|
|
}
|
|
return saved
|
|
}
|
|
|
|
function restorePasteboard(pb, saved) {
|
|
pb.clearContents
|
|
if (saved.length && !pb.writeObjects($(saved))) throw Error('Cannot restore clipboard')
|
|
flushPasteboard(saved.length)
|
|
}
|
|
|
|
function withStagedPasteboard(items, action, stealthRestore = false) {
|
|
const pb = $.NSPasteboard.generalPasteboard
|
|
const originalCount = pb.changeCount
|
|
// A deferred flavor can time out. Preserve all readable flavors and keep input working.
|
|
const saved = savePasteboard(pb, true, stealthRestore)
|
|
if (pb.changeCount !== originalCount) throw Error('Pasteboard changed during backup')
|
|
let stagedCount = pb.clearContents
|
|
try {
|
|
if (!pb.writeObjects($(items))) throw Error('Cannot stage clipboard')
|
|
stagedCount = pb.changeCount
|
|
return action()
|
|
} finally {
|
|
if (pb.changeCount === stagedCount) restorePasteboard(pb, saved)
|
|
}
|
|
}
|
|
|
|
function injectText(textFile, url, inputID) {
|
|
if (!/^[0-9]+$/.test(inputID)) throw Error('Invalid text input ID')
|
|
const value = $.NSString.stringWithContentsOfFileEncodingError(textFile, $.NSUTF8StringEncoding, null)
|
|
const item = $.NSPasteboardItem.alloc.init
|
|
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
|
throw Error('Cannot stage text')
|
|
return withStagedPasteboard([addStealth(item)], () => {
|
|
postToHost(url + '?id=' + inputID)
|
|
return 'ok'
|
|
})
|
|
}
|
|
|
|
function pasteCore(hitArgs, expected, bundleId, mode, url, id, items) {
|
|
const {top, windows} = hit(hitArgs)
|
|
if (!top || String(top.kCGWindowNumber || 0) !== expected) return 'cancelled'
|
|
const ownerApp = top.kCGWindowOwnerPID
|
|
? $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID) : null
|
|
const isTopOfApp = windows.find(w => w.kCGWindowOwnerPID === top.kCGWindowOwnerPID)?.kCGWindowNumber === top.kCGWindowNumber
|
|
const fm0 = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
|
const alreadyActive = !!(fm0 && !fm0.isNil() && fm0.processIdentifier === top.kCGWindowOwnerPID)
|
|
let activated = false
|
|
if (ownerApp && isTopOfApp) {
|
|
if (bundleId === 'com.apple.finder' && ownerApp.bundleURL && !ownerApp.bundleURL.isNil()) {
|
|
$.NSWorkspace.sharedWorkspace.openURL(ownerApp.bundleURL)
|
|
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.15))
|
|
activated = true
|
|
} else if (!alreadyActive) {
|
|
ownerApp.activateWithOptions($.NSApplicationActivateIgnoringOtherApps)
|
|
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.12))
|
|
activated = true
|
|
}
|
|
}
|
|
if (activated && !(hit(hitArgs).windows || []).some(w => String(w.kCGWindowNumber) === expected)) return 'cancelled'
|
|
const fm = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
|
const activateClick = !!(top.kCGWindowOwnerPID && (!isTopOfApp || !fm || fm.isNil() || fm.processIdentifier !== top.kCGWindowOwnerPID))
|
|
const newItems = items.map(path => {
|
|
const item = $.NSPasteboardItem.alloc.init
|
|
if (mode === 'files') {
|
|
const png = items.length === 1 && bundleId !== 'com.apple.finder' ? readImagePNG(path) : null
|
|
if ((!png || !browserBundles.has(bundleId)) &&
|
|
!item.setStringForType($.NSURL.fileURLWithPath(path).absoluteString, $.NSPasteboardTypeFileURL))
|
|
throw Error('Cannot stage file')
|
|
if (png && !item.setDataForType(png, $.NSPasteboardTypePNG)) throw Error('Cannot stage PNG')
|
|
} else if (mode === 'text' || mode === 'text-raw') {
|
|
const value = mode === 'text-raw' ? $(path) : $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)
|
|
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
|
throw Error('Cannot stage text')
|
|
} else throw Error('Invalid paste mode')
|
|
return addStealth(item)
|
|
})
|
|
return withStagedPasteboard(newItems, () => {
|
|
requestPaste(url, id, activateClick, resolveCommandKey(), bundleId === 'com.apple.finder' ? 220 : 0)
|
|
return 'pasted'
|
|
}, true)
|
|
}
|
|
|
|
function parseEventData(eventFile) {
|
|
const ev = JSON.parse($.NSString.stringWithContentsOfFileEncodingError(eventFile, $.NSUTF8StringEncoding, null).js)
|
|
if (!ev || typeof ev.drop_id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ev.drop_id)) throw Error('Invalid drop ID')
|
|
if (!Number.isInteger(ev.display_index) || ev.display_index < 0 ||
|
|
![ev.norm_x, ev.norm_y].every(n => Number.isFinite(n) && n >= 0 && n <= 1) ||
|
|
[ev.webdav_drop, ev.in_image].some(v => v !== undefined && typeof v !== 'boolean')) throw Error('Invalid drop location')
|
|
if (ev.kind === undefined) ev.kind = 'files'
|
|
ev.webdav_drop = ev.webdav_drop === true
|
|
ev.in_image = ev.in_image === true
|
|
if (ev.kind === 'text') {
|
|
if (typeof ev.text !== 'string' || !ev.text.length) throw Error('Invalid drop text')
|
|
} else {
|
|
if (ev.kind !== 'files') throw Error('Invalid drop kind')
|
|
const safePath = n => typeof n === 'string' && !/[\\\n\r\0\t]/.test(n) &&
|
|
n.split('/').every(segment => segment && segment !== '.' && segment !== '..')
|
|
if (!Array.isArray(ev.items) || !ev.items.length || !ev.items.every(safePath)) throw Error('Invalid drop item')
|
|
ev.targets = ev.target_paths === undefined ? ev.items : ev.target_paths
|
|
if (!Array.isArray(ev.targets) || ev.targets.length !== ev.items.length || !ev.targets.every(safePath))
|
|
throw Error('Invalid drop target path')
|
|
}
|
|
return ev
|
|
}
|
|
|
|
function eventLines(ev) {
|
|
const header = [ev.drop_id, ev.kind, ev.webdav_drop, ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].join('\t')
|
|
return [header].concat(ev.kind === 'files' ? ev.items.map((src, i) => src + '\t' + ev.targets[i]) : [])
|
|
}
|
|
|
|
function encodeAck(drop_id, status, target_kind, label, error, names) {
|
|
return JSON.stringify({drop_id, status, target_kind, target_label: label || undefined,
|
|
error: error || undefined, placed_names: names.length ? names : undefined})
|
|
}
|
|
|
|
function mountHealthy(paths) {
|
|
try {
|
|
return paths.length > 0 && paths.every(p => {
|
|
const ref = $.NSURL.fileURLWithPath(p).fileReferenceURL
|
|
return ref && (typeof ref.isNil !== 'function' || !ref.isNil())
|
|
})
|
|
} catch (_) { return false }
|
|
}
|
|
|
|
function importPhotos(paths) {
|
|
Application('com.apple.Photos').import(paths.map(p => Path(p)), {skipCheckDuplicates: false})
|
|
return 'ok'
|
|
}
|
|
|
|
function photosError(err) {
|
|
const msg = String(err && err.message || err || '').replace(/[\r\n\t]+/g, ' ').trim()
|
|
if (/1743|not authorized|permission|privilege/i.test(msg)) return 'Photos import blocked: allow Automation access to Photos in macOS Privacy & Security'
|
|
return msg ? 'Photos import failed: ' + msg.slice(0, 140) : 'Photos import failed'
|
|
}
|
|
|
|
function runDrop(eventFile, mount, url) {
|
|
const ev = parseEventData(eventFile)
|
|
const hitArgs = [ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].map(String)
|
|
const target = resolve(hitArgs)
|
|
const [kind, label, meta, expected] = target.split('\t')
|
|
function done(status) {
|
|
return 'done\t' + encodeAck(ev.drop_id, status, status === 'cancelled' ? 'cancelled' : kind,
|
|
status === 'cancelled' ? '' : label, '', [])
|
|
}
|
|
function perform(mode, paths) {
|
|
try {
|
|
if (kind === 'photos') {
|
|
importPhotos(paths)
|
|
return done('placed')
|
|
}
|
|
return done(pasteCore(hitArgs, expected, meta, mode, url, ev.drop_id, paths))
|
|
} catch (err) {
|
|
return 'done\t' + encodeAck(ev.drop_id, 'failed', kind, label,
|
|
kind === 'photos' ? photosError(err) : 'Paste failed', [])
|
|
}
|
|
}
|
|
if (kind === 'none' || (ev.kind === 'text' && kind !== 'window')) return done('cancelled')
|
|
if (ev.kind === 'text') return perform('text-raw', [ev.text])
|
|
if ((kind === 'window' || kind === 'photos') && ev.webdav_drop && mount) {
|
|
const dir = mount + '/' + ev.drop_id
|
|
const fm = $.NSFileManager.defaultManager
|
|
const dirRef = Ref()
|
|
const paths = ev.items.map(src => dir + '/' + src)
|
|
if (fm.fileExistsAtPathIsDirectory(dir, dirRef) && dirRef[0] && mountHealthy([mount, dir]) &&
|
|
paths.every(p => fm.fileExistsAtPath(p))) {
|
|
return perform('files', paths)
|
|
}
|
|
}
|
|
const [header, ...items] = eventLines(ev)
|
|
return ['fallback', header, target].concat(items).join('\n')
|
|
}
|
|
|
|
// Short-lived osascript can exit before pboard commits multi-item XPC payloads unless the run loop runs briefly.
|
|
function flushPasteboard(count) {
|
|
const secs = Math.min(0.25, 0.06 + count * 0.0005)
|
|
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(secs))
|
|
}
|
|
|
|
function readClipFiles() {
|
|
const items = $.NSPasteboard.generalPasteboard.pasteboardItems
|
|
const urls = []
|
|
if (items && !items.isNil()) {
|
|
for (let i = 0; i < items.count; i++) {
|
|
const value = items.objectAtIndex(i).stringForType($.NSPasteboardTypeFileURL)
|
|
if (value && !value.isNil()) {
|
|
const url = ObjC.unwrap(value)
|
|
if (url) urls.push(url)
|
|
}
|
|
}
|
|
}
|
|
if (!urls.length && typeof $.NSPasteboard.generalPasteboard.propertyListForType === 'function') {
|
|
const paths = ObjC.deepUnwrap($.NSPasteboard.generalPasteboard.propertyListForType('NSFilenamesPboardType'))
|
|
if (Array.isArray(paths)) {
|
|
for (const p of paths) {
|
|
if (typeof p === 'string' && p.startsWith('/'))
|
|
urls.push(ObjC.unwrap($.NSURL.fileURLWithPath(p).absoluteString))
|
|
}
|
|
}
|
|
}
|
|
if (!urls.length) throw Error('No clip files')
|
|
return urls.join('\n')
|
|
}
|
|
|
|
function textFile(path) {
|
|
const value = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)
|
|
if (!value || value.isNil()) throw Error('Cannot read clipboard file')
|
|
return value.js
|
|
}
|
|
|
|
function localClipPaths(list, roots) {
|
|
const comparePath = value => value.normalize('NFC').toLowerCase().replace(/\/+$/, '')
|
|
const hosted = roots.filter(Boolean).flatMap(p => {
|
|
const path = $(p)
|
|
return [p, ObjC.unwrap(path.stringByStandardizingPath), ObjC.unwrap(path.stringByResolvingSymlinksInPath)]
|
|
}).filter(p => typeof p === 'string' && p.startsWith('/')).map(comparePath)
|
|
const urls = textFile(list).split('\n').filter(Boolean)
|
|
if (urls.length > 256) throw Error('Too many clipboard files')
|
|
const paths = new Set()
|
|
for (const raw of urls) {
|
|
const url = $.NSURL.URLWithString(raw)
|
|
if (!url || url.isNil() || !url.isFileURL) continue
|
|
const host = ObjC.unwrap(url.host)
|
|
if (host && host !== 'localhost') continue
|
|
const pathURL = raw.startsWith('file:///.file/') ? url.filePathURL : url
|
|
if (!pathURL || pathURL.isNil()) continue
|
|
const path = pathURL.path
|
|
if (!path || path.isNil()) continue
|
|
const names = [ObjC.unwrap(path), ObjC.unwrap(path.stringByStandardizingPath), ObjC.unwrap(path.stringByResolvingSymlinksInPath)]
|
|
// A selected ancestor would recursively include the private fallback cache.
|
|
if (names.filter(n => typeof n === 'string').map(comparePath)
|
|
.some(n => hosted.some(root => n === root || n.startsWith(root + '/') || root.startsWith(n + '/')))) continue
|
|
const file = (names[1] || names[0])?.replace(/\/+$/, '')
|
|
if (file?.startsWith('/') && !/[\x00-\x1f\x7f]/.test(file)) paths.add(file)
|
|
}
|
|
return Array.from(paths).join('\n')
|
|
}
|
|
|
|
function readClipManifest(manifestFile) {
|
|
const ev = JSON.parse(textFile(manifestFile))
|
|
const safeName = name => typeof name === 'string' && name.length > 0 && name !== '.' &&
|
|
name !== '..' && !/[/\\\0\r\n\t]/.test(name)
|
|
if (!ev || typeof ev.drop_id !== 'string' || !/^clip-[a-f0-9]{16}$/.test(ev.drop_id) ||
|
|
!Array.isArray(ev.items) || !ev.items.length || ev.items.length > 256 ||
|
|
!ev.items.every(safeName) || new Set(ev.items).size !== ev.items.length) throw Error('Invalid clipboard manifest')
|
|
return ev
|
|
}
|
|
|
|
function validateClipArchive(manifestFile, entriesFile) {
|
|
const ev = readClipManifest(manifestFile)
|
|
const roots = new Set(ev.items)
|
|
const found = new Set()
|
|
const seen = new Set()
|
|
const entries = textFile(entriesFile).split('\n')
|
|
if (entries.pop() !== '' || entries.length > 2000) throw Error('Invalid clipboard archive size')
|
|
for (const entry of entries) {
|
|
const path = entry.replace(/\/$/, '')
|
|
const parts = path.split('/')
|
|
if (!roots.has(parts[0]) || parts.length > 32 || seen.has(path) ||
|
|
parts.some(p => !p || p === '.' || p === '..' || /[\\\x00-\x1f\x7f]/.test(p)))
|
|
throw Error('Invalid clipboard archive path')
|
|
seen.add(path)
|
|
if (parts.length === 1) found.add(parts[0])
|
|
}
|
|
if (found.size !== roots.size) throw Error('Clipboard archive does not match its manifest')
|
|
return 'ok'
|
|
}
|
|
|
|
function mountedClipboardSourcesReadable(paths) {
|
|
// Metadata can remain visible when WebDAV can no longer serve the item.
|
|
// Give the entire probe a deadline, without downloading the selection.
|
|
const check = `
|
|
alarm 5;
|
|
for my $path (@ARGV) {
|
|
if (-d $path) {
|
|
opendir(my $dir, $path) or exit 1;
|
|
while (1) {
|
|
$! = 0;
|
|
my $name = readdir($dir);
|
|
exit 1 if !defined($name) && $!;
|
|
last if !defined($name) || ($name ne '.' && $name ne '..');
|
|
}
|
|
closedir($dir) or exit 1;
|
|
} elsif (-f $path) {
|
|
open(my $file, '<:raw', $path) or exit 1;
|
|
defined(sysread($file, my $byte, 1)) or exit 1;
|
|
close($file) or exit 1;
|
|
} else {
|
|
exit 1;
|
|
}
|
|
}
|
|
`
|
|
try {
|
|
const task = $.NSTask.alloc.init
|
|
task.launchPath = '/usr/bin/perl'
|
|
task.arguments = $(['-e', check, '--', ...paths])
|
|
task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.standardError = $.NSFileHandle.fileHandleWithNullDevice
|
|
task.launch
|
|
task.waitUntilExit
|
|
return task.terminationStatus === 0
|
|
} catch (_) { return false }
|
|
}
|
|
|
|
function writeClipFiles(manifestFile, mount, expectedCount, cached = false) {
|
|
if (!mount) return 'remount'
|
|
const ev = readClipManifest(manifestFile)
|
|
const fm = $.NSFileManager.defaultManager
|
|
const dir = mount + '/' + ev.drop_id
|
|
const isDir = Ref()
|
|
const exists = () => fm.fileExistsAtPathIsDirectory(dir, isDir) && isDir[0]
|
|
if (!exists()) {
|
|
fm.contentsOfDirectoryAtPathError(mount, null)
|
|
if (!exists()) return 'remount'
|
|
}
|
|
const paths = ev.items.map(name => dir + '/' + name)
|
|
if ((!cached && !mountHealthy([mount, dir])) || !paths.every(p => fm.fileExistsAtPath(p))) return 'remount'
|
|
if (!cached && !mountedClipboardSourcesReadable(paths)) return 'unreadable'
|
|
const urls = paths.map(p => $.NSURL.fileURLWithPath(p).absoluteString)
|
|
const newItems = urls.map(url => {
|
|
const item = $.NSPasteboardItem.alloc.init
|
|
if (!item.setStringForType(url, $.NSPasteboardTypeFileURL))
|
|
throw Error('Invalid clipboard file URL')
|
|
return item
|
|
})
|
|
const pb = $.NSPasteboard.generalPasteboard
|
|
const originalCount = pb.changeCount
|
|
if (expectedCount && String(originalCount) !== expectedCount) return 'changed'
|
|
const saved = savePasteboard(pb, false, false)
|
|
if (pb.changeCount !== originalCount) return 'changed'
|
|
let writtenCount = pb.clearContents
|
|
try {
|
|
if (!pb.writeObjects($(newItems))) throw Error('Clipboard write failed')
|
|
writtenCount = pb.changeCount
|
|
flushPasteboard(newItems.length)
|
|
if (pb.changeCount !== writtenCount) return 'changed'
|
|
if (readClipFiles() !== urls.map(url => ObjC.unwrap(url)).join('\n'))
|
|
throw Error('Clipboard file readback did not match')
|
|
return 'ok'
|
|
} catch (err) {
|
|
if (pb.changeCount === writtenCount) restorePasteboard(pb, saved)
|
|
throw err
|
|
}
|
|
}
|
|
|
|
function run(argv) {
|
|
const [mode, ...args] = argv
|
|
if (mode === 'inject-text') return injectText(...args)
|
|
if (mode === 'read-clip-files') return readClipFiles()
|
|
if (mode === 'local-clip-paths') return localClipPaths(args[0], args.slice(1))
|
|
if (mode === 'clip-manifest-id') return readClipManifest(args[0]).drop_id
|
|
if (mode === 'validate-clip-archive') return validateClipArchive(...args)
|
|
if (mode === 'write-clip-files') return writeClipFiles(args[0], args[1], args[2], args[3] === 'cache')
|
|
if (mode === 'run-drop') return runDrop(...args)
|
|
if (mode === 'resolve') return resolve(args)
|
|
if (mode === 'check-mount') {
|
|
if (!mountHealthy(args)) throw Error('Unreachable mount')
|
|
return 'ok'
|
|
}
|
|
if (mode === 'paste-drop') {
|
|
const [, , , expected, bundleId, kind, url, id, ...paths] = args
|
|
return pasteCore(args.slice(0, 3), expected, bundleId, kind, url, id, paths)
|
|
}
|
|
if (mode === 'import-photos') return importPhotos(args)
|
|
if (mode === 'parse-event') {
|
|
const ev = parseEventData(args[0])
|
|
if (ev.kind === 'text' && (!args[1] ||
|
|
!$.NSString.stringWithString(ev.text).writeToFileAtomicallyEncodingError(args[1], true, $.NSUTF8StringEncoding, null)))
|
|
throw Error('Invalid drop text')
|
|
return eventLines(ev).join('\n')
|
|
}
|
|
if (mode === 'encode-ack') return encodeAck(...args.slice(0, 5), args.slice(5))
|
|
throw Error('Unknown drop command')
|
|
}
|