@windowkit/appkit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,399 @@
1
+ // @windowkit/appkit permissions.mm — the macOS privacy (TCC) authorizations
2
+ // an app may need: the current status, the system prompt where a framework
3
+ // offers one, and the Settings pane for the grants that can only happen there.
4
+ //
5
+ // Mechanism only, policy stays in the renderer. Each kind is one framework's
6
+ // own pair of calls, and a switch over the kind is the whole bridge:
7
+ //
8
+ // camera, microphone AVCaptureDevice authorizationStatusForMediaType: /
9
+ // requestAccessForMediaType: — the completion lands on
10
+ // an arbitrary queue and comes back through a
11
+ // thread-safe function
12
+ // screen-recording CGPreflightScreenCaptureAccess /
13
+ // CGRequestScreenCaptureAccess
14
+ // accessibility AXIsProcessTrusted / AXIsProcessTrustedWithOptions
15
+ // with the prompt option
16
+ // input-monitoring IOHIDCheckAccess / IOHIDRequestAccess (listen)
17
+ // automation AEDeterminePermissionToAutomateTarget for one target
18
+ // bundle id; the asking form blocks while the prompt is
19
+ // up, so it runs off the main thread
20
+ // location CLLocationManager.authorizationStatus /
21
+ // requestWhenInUseAuthorization, answered through the
22
+ // delegate on the main run loop — i.e. during the pump
23
+ //
24
+ // Every status that crosses to JS is one of 'authorized' | 'denied' |
25
+ // 'restricted' | 'notDetermined'. Screen recording and accessibility only
26
+ // ever answer with a bool, so they never say notDetermined; their "request"
27
+ // posts the system's own go-to-Settings dialog and returns at once — the
28
+ // user finishes the grant in Settings, which is what openPrivacySettings is
29
+ // for. The folder grants (Desktop, Documents, Downloads) need nothing here:
30
+ // reading the directory is the prompt, and EPERM is the denial.
31
+ //
32
+ // Every request answers asynchronously, once, through the callback — never
33
+ // inside the requesting call — and a pending request holds the event loop
34
+ // open like pending I/O until the user has answered.
35
+
36
+ #include <napi.h>
37
+ #import <Cocoa/Cocoa.h>
38
+ #import <AVFoundation/AVFoundation.h>
39
+ #import <CoreLocation/CoreLocation.h>
40
+ #import <ApplicationServices/ApplicationServices.h>
41
+ #import <IOKit/hidsystem/IOHIDLib.h>
42
+
43
+ #include <cstring>
44
+ #include <string>
45
+
46
+ static const char* const kAuthorized = "authorized";
47
+ static const char* const kDenied = "denied";
48
+ static const char* const kRestricted = "restricted";
49
+ static const char* const kNotDetermined = "notDetermined";
50
+
51
+ enum class Kind {
52
+ Camera,
53
+ Microphone,
54
+ ScreenRecording,
55
+ Accessibility,
56
+ InputMonitoring,
57
+ Automation,
58
+ Location,
59
+ };
60
+
61
+ static const char* const kKindNames =
62
+ "camera, microphone, screen-recording, accessibility, input-monitoring, "
63
+ "automation, location";
64
+
65
+ static bool ParseKind(const std::string& s, Kind* out) {
66
+ if (s == "camera") *out = Kind::Camera;
67
+ else if (s == "microphone") *out = Kind::Microphone;
68
+ else if (s == "screen-recording") *out = Kind::ScreenRecording;
69
+ else if (s == "accessibility") *out = Kind::Accessibility;
70
+ else if (s == "input-monitoring") *out = Kind::InputMonitoring;
71
+ else if (s == "automation") *out = Kind::Automation;
72
+ else if (s == "location") *out = Kind::Location;
73
+ else return false;
74
+ return true;
75
+ }
76
+
77
+ // (kind, opts?) — the kind string, and for 'automation' the target bundle id
78
+ // from opts.target. Throws a TypeError and returns false on a bad shape.
79
+ static bool ParseKindArgs(const char* fn, const Napi::CallbackInfo& info,
80
+ Kind* kind, NSString** target) {
81
+ Napi::Env env = info.Env();
82
+ if (info.Length() < 1 || !info[0].IsString()) {
83
+ Napi::TypeError::New(env, std::string(fn) + ": expected a kind string (" +
84
+ kKindNames + ")")
85
+ .ThrowAsJavaScriptException();
86
+ return false;
87
+ }
88
+ std::string name = info[0].As<Napi::String>().Utf8Value();
89
+ if (!ParseKind(name, kind)) {
90
+ Napi::TypeError::New(env, std::string(fn) + ": unknown kind '" + name +
91
+ "' (" + kKindNames + ")")
92
+ .ThrowAsJavaScriptException();
93
+ return false;
94
+ }
95
+ *target = nil;
96
+ if (*kind == Kind::Automation) {
97
+ Napi::Value t;
98
+ if (info.Length() > 1 && info[1].IsObject()) {
99
+ t = info[1].As<Napi::Object>().Get("target");
100
+ }
101
+ if (t.IsEmpty() || !t.IsString()) {
102
+ Napi::TypeError::New(env, std::string(fn) +
103
+ ": 'automation' needs { target: <bundle "
104
+ "id of the app to send Apple Events to> }")
105
+ .ThrowAsJavaScriptException();
106
+ return false;
107
+ }
108
+ std::string s = t.As<Napi::String>().Utf8Value();
109
+ *target = [NSString stringWithUTF8String:s.c_str()];
110
+ }
111
+ return true;
112
+ }
113
+
114
+ // --- per-framework status --------------------------------------------------
115
+
116
+ static const char* AVStatus(AVMediaType type) {
117
+ switch ([AVCaptureDevice authorizationStatusForMediaType:type]) {
118
+ case AVAuthorizationStatusAuthorized: return kAuthorized;
119
+ case AVAuthorizationStatusDenied: return kDenied;
120
+ case AVAuthorizationStatusRestricted: return kRestricted;
121
+ case AVAuthorizationStatusNotDetermined:
122
+ default: return kNotDetermined;
123
+ }
124
+ }
125
+
126
+ static const char* HidStatus() {
127
+ switch (IOHIDCheckAccess(kIOHIDRequestTypeListenEvent)) {
128
+ case kIOHIDAccessTypeGranted: return kAuthorized;
129
+ case kIOHIDAccessTypeDenied: return kDenied;
130
+ case kIOHIDAccessTypeUnknown:
131
+ default: return kNotDetermined;
132
+ }
133
+ }
134
+
135
+ static const char* LocationStatusOf(CLLocationManager* m) {
136
+ switch (m.authorizationStatus) {
137
+ // macOS has only the one grant (the SDK marks WhenInUse iOS-only)
138
+ case kCLAuthorizationStatusAuthorizedAlways: return kAuthorized;
139
+ case kCLAuthorizationStatusDenied: return kDenied;
140
+ case kCLAuthorizationStatusRestricted: return kRestricted;
141
+ case kCLAuthorizationStatusNotDetermined:
142
+ default: return kNotDetermined;
143
+ }
144
+ }
145
+
146
+ // One manager, created on the main thread, answers status queries; requests
147
+ // get their own (see CALLocationRequest) so the delegate traffic is per call.
148
+ static CLLocationManager* LocationStatusManager() {
149
+ static CLLocationManager* m = nil;
150
+ if (!m) m = [CLLocationManager new];
151
+ return m;
152
+ }
153
+
154
+ // TCC's answer for sending Apple Events to `bundleId`. With `ask`, the call
155
+ // blocks while the consent dialog is up. procNotFound means the target is
156
+ // not running — TCC only answers for a running target, so the caller turns
157
+ // that into an error rather than a status.
158
+ static OSStatus AutomationPermission(NSString* bundleId, bool ask) {
159
+ const char* s = bundleId.UTF8String;
160
+ AEAddressDesc target;
161
+ OSErr err = AECreateDesc(typeApplicationBundleID, s, strlen(s), &target);
162
+ if (err != noErr) return err;
163
+ OSStatus st = AEDeterminePermissionToAutomateTarget(&target, typeWildCard,
164
+ typeWildCard, ask);
165
+ AEDisposeDesc(&target);
166
+ return st;
167
+ }
168
+
169
+ static const char* AutomationStatus(OSStatus st) {
170
+ if (st == noErr) return kAuthorized;
171
+ if (st == errAEEventWouldRequireUserConsent) return kNotDetermined;
172
+ return kDenied; // errAEEventNotPermitted, or anything else TCC refused
173
+ }
174
+
175
+ static bool ThrowIfTargetNotRunning(Napi::Env env, const char* fn,
176
+ NSString* target, OSStatus st) {
177
+ if (st != procNotFound) return false;
178
+ Napi::Error::New(env, std::string(fn) + ": automation target '" +
179
+ target.UTF8String +
180
+ "' is not running; TCC only answers for a "
181
+ "running target")
182
+ .ThrowAsJavaScriptException();
183
+ return true;
184
+ }
185
+
186
+ // --- the answer path -------------------------------------------------------
187
+
188
+ // Deliver one status to the request's callback as cb(granted, status) on the
189
+ // JS thread, from any thread, then let the thread-safe function go. The
190
+ // status strings are the static literals above, so a bare pointer travels.
191
+ static void Answer(Napi::ThreadSafeFunction tsfn, const char* status) {
192
+ tsfn.BlockingCall(
193
+ const_cast<char*>(status),
194
+ [](Napi::Env env, Napi::Function cb, char* s) {
195
+ cb.Call({Napi::Boolean::New(env, strcmp(s, kAuthorized) == 0),
196
+ Napi::String::New(env, s)});
197
+ });
198
+ tsfn.Release();
199
+ }
200
+
201
+ // A location request: its own CLLocationManager whose delegate reports the
202
+ // decision. The delegate is also told the current status right after it is
203
+ // set, which is notDetermined while the prompt is still up — that echo is
204
+ // skipped; the first determined status answers.
205
+ @interface CALLocationRequest : NSObject <CLLocationManagerDelegate> {
206
+ @public
207
+ CLLocationManager* mgr_;
208
+ Napi::ThreadSafeFunction tsfn_;
209
+ bool done_;
210
+ }
211
+ @end
212
+
213
+ static NSMutableArray<CALLocationRequest*>* gLocationRequests = nil;
214
+
215
+ @implementation CALLocationRequest
216
+ - (void)locationManagerDidChangeAuthorization:(CLLocationManager*)m {
217
+ if (done_) return;
218
+ const char* s = LocationStatusOf(m);
219
+ if (s == kNotDetermined) return;
220
+ done_ = true;
221
+ m.delegate = nil;
222
+ Answer(tsfn_, s);
223
+ [gLocationRequests removeObject:self];
224
+ }
225
+ @end
226
+
227
+ static void StartLocationRequest(Napi::ThreadSafeFunction tsfn) {
228
+ CALLocationRequest* r = [CALLocationRequest new];
229
+ r->tsfn_ = tsfn;
230
+ r->done_ = false;
231
+ r->mgr_ = [CLLocationManager new];
232
+ r->mgr_.delegate = r;
233
+ if (!gLocationRequests) gLocationRequests = [NSMutableArray new];
234
+ [gLocationRequests addObject:r];
235
+ [r->mgr_ requestWhenInUseAuthorization];
236
+ }
237
+
238
+ // --- the natives -----------------------------------------------------------
239
+
240
+ // authorizationStatus(kind, opts?) -> 'authorized' | 'denied' | 'restricted'
241
+ // | 'notDetermined'. Never prompts.
242
+ static Napi::Value AuthorizationStatus(const Napi::CallbackInfo& info) {
243
+ Napi::Env env = info.Env();
244
+ Kind kind;
245
+ NSString* target;
246
+ if (!ParseKindArgs("authorizationStatus", info, &kind, &target))
247
+ return env.Undefined();
248
+ @autoreleasepool {
249
+ const char* s = kNotDetermined;
250
+ switch (kind) {
251
+ case Kind::Camera: s = AVStatus(AVMediaTypeVideo); break;
252
+ case Kind::Microphone: s = AVStatus(AVMediaTypeAudio); break;
253
+ case Kind::ScreenRecording:
254
+ s = CGPreflightScreenCaptureAccess() ? kAuthorized : kDenied;
255
+ break;
256
+ case Kind::Accessibility:
257
+ s = AXIsProcessTrusted() ? kAuthorized : kDenied;
258
+ break;
259
+ case Kind::InputMonitoring: s = HidStatus(); break;
260
+ case Kind::Automation: {
261
+ OSStatus st = AutomationPermission(target, false);
262
+ if (ThrowIfTargetNotRunning(env, "authorizationStatus", target, st))
263
+ return env.Undefined();
264
+ s = AutomationStatus(st);
265
+ break;
266
+ }
267
+ case Kind::Location: s = LocationStatusOf(LocationStatusManager()); break;
268
+ }
269
+ return Napi::String::New(env, s);
270
+ }
271
+ }
272
+
273
+ // requestAuthorization(kind, opts?, cb) — raises the system prompt where the
274
+ // framework offers one; cb(granted, status) once, asynchronously.
275
+ static Napi::Value RequestAuthorization(const Napi::CallbackInfo& info) {
276
+ Napi::Env env = info.Env();
277
+ Kind kind;
278
+ NSString* target;
279
+ if (!ParseKindArgs("requestAuthorization", info, &kind, &target))
280
+ return env.Undefined();
281
+ size_t cbAt = info.Length() > 1 && info[1].IsFunction() ? 1 : 2;
282
+ if (info.Length() <= cbAt || !info[cbAt].IsFunction()) {
283
+ Napi::TypeError::New(env, "requestAuthorization: expected a callback "
284
+ "(kind, opts?, cb)")
285
+ .ThrowAsJavaScriptException();
286
+ return env.Undefined();
287
+ }
288
+ @autoreleasepool {
289
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
290
+ env, info[cbAt].As<Napi::Function>(), "appkit:requestAuthorization",
291
+ 0, 1);
292
+ switch (kind) {
293
+ case Kind::Camera:
294
+ case Kind::Microphone: {
295
+ AVMediaType type =
296
+ kind == Kind::Camera ? AVMediaTypeVideo : AVMediaTypeAudio;
297
+ [AVCaptureDevice requestAccessForMediaType:type
298
+ completionHandler:^(BOOL) {
299
+ Answer(tsfn, AVStatus(type));
300
+ }];
301
+ break;
302
+ }
303
+ case Kind::ScreenRecording:
304
+ // prompts once (the go-to-Settings dialog) when not yet asked, and
305
+ // returns the current grant either way
306
+ Answer(tsfn, CGRequestScreenCaptureAccess() ? kAuthorized : kDenied);
307
+ break;
308
+ case Kind::Accessibility: {
309
+ NSDictionary* opts =
310
+ @{(__bridge NSString*)kAXTrustedCheckOptionPrompt : @YES};
311
+ bool ok = AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)opts);
312
+ Answer(tsfn, ok ? kAuthorized : kDenied);
313
+ break;
314
+ }
315
+ case Kind::InputMonitoring: {
316
+ // the prompt is posted and the call returns; a still-open prompt
317
+ // reads back as notDetermined
318
+ bool ok = IOHIDRequestAccess(kIOHIDRequestTypeListenEvent);
319
+ Answer(tsfn, ok ? kAuthorized : HidStatus());
320
+ break;
321
+ }
322
+ case Kind::Automation: {
323
+ OSStatus st = AutomationPermission(target, false);
324
+ if (ThrowIfTargetNotRunning(env, "requestAuthorization", target, st)) {
325
+ tsfn.Release();
326
+ return env.Undefined();
327
+ }
328
+ if (st != errAEEventWouldRequireUserConsent) {
329
+ Answer(tsfn, AutomationStatus(st));
330
+ break;
331
+ }
332
+ // the asking form blocks until the user answers the consent dialog:
333
+ // off the main thread so node's loop keeps turning meanwhile
334
+ NSString* bundleId = target;
335
+ dispatch_async(
336
+ dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
337
+ Answer(tsfn, AutomationStatus(AutomationPermission(bundleId, true)));
338
+ });
339
+ break;
340
+ }
341
+ case Kind::Location: StartLocationRequest(tsfn); break;
342
+ }
343
+ }
344
+ return env.Undefined();
345
+ }
346
+
347
+ // openPrivacySettings(kind?) -> bool — best-effort deep link to the Privacy
348
+ // pane of System Settings, or its top level with no kind.
349
+ static Napi::Value OpenPrivacySettings(const Napi::CallbackInfo& info) {
350
+ Napi::Env env = info.Env();
351
+ std::string kind;
352
+ if (info.Length() > 0 && !info[0].IsUndefined() && !info[0].IsNull()) {
353
+ if (!info[0].IsString()) {
354
+ Napi::TypeError::New(env, "openPrivacySettings: expected a kind string")
355
+ .ThrowAsJavaScriptException();
356
+ return env.Undefined();
357
+ }
358
+ kind = info[0].As<Napi::String>().Utf8Value();
359
+ }
360
+ const char* anchor = nullptr;
361
+ if (kind.empty()) anchor = "Privacy";
362
+ else if (kind == "camera") anchor = "Privacy_Camera";
363
+ else if (kind == "microphone") anchor = "Privacy_Microphone";
364
+ else if (kind == "screen-recording") anchor = "Privacy_ScreenCapture";
365
+ else if (kind == "accessibility") anchor = "Privacy_Accessibility";
366
+ else if (kind == "input-monitoring") anchor = "Privacy_ListenEvent";
367
+ else if (kind == "automation") anchor = "Privacy_Automation";
368
+ else if (kind == "location") anchor = "Privacy_LocationServices";
369
+ else if (kind == "files-and-folders") anchor = "Privacy_FilesAndFolders";
370
+ else if (kind == "full-disk-access") anchor = "Privacy_AllFiles";
371
+ if (!anchor) {
372
+ Napi::TypeError::New(env, "openPrivacySettings: unknown kind '" + kind +
373
+ "' (" + kKindNames +
374
+ ", files-and-folders, full-disk-access)")
375
+ .ThrowAsJavaScriptException();
376
+ return env.Undefined();
377
+ }
378
+ @autoreleasepool {
379
+ NSString* url = [NSString
380
+ stringWithFormat:@"x-apple.systempreferences:com.apple.preference."
381
+ @"security?%s",
382
+ anchor];
383
+ bool ok = [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:url]];
384
+ return Napi::Boolean::New(env, ok);
385
+ }
386
+ }
387
+
388
+ // ---------------------------------------------------------------------------
389
+ // registration (called from addon.mm's Init)
390
+ // ---------------------------------------------------------------------------
391
+
392
+ void InitPermissions(Napi::Env env, Napi::Object exports) {
393
+ exports.Set("authorizationStatus",
394
+ Napi::Function::New(env, AuthorizationStatus));
395
+ exports.Set("requestAuthorization",
396
+ Napi::Function::New(env, RequestAuthorization));
397
+ exports.Set("openPrivacySettings",
398
+ Napi::Function::New(env, OpenPrivacySettings));
399
+ }