### Install node-mac-permissions
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Install the package using npm.
```bash
npm i node-mac-permissions
```
--------------------------------
### Native Error Handling Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Illustrates how errors originating from the native macOS implementation (permissions.mm) are handled.
```javascript
try {
await askForCameraAccess()
} catch (error) {
// Native macOS error message
// Stack: thrown in permissions.mm native code
}
```
--------------------------------
### Complete Info.plist Example for Permissions
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
This XML snippet shows a comprehensive Info.plist structure with usage descriptions for common macOS permissions. Ensure each permission used by your application has a corresponding entry.
```xml
CFBundleExecutable
MyApp
CFBundleName
My Application
CFBundleVersion
1.0.0
NSCameraUsageDescription
We need access to your camera to enable video conferencing.
NSMicrophoneUsageDescription
We need access to your microphone for audio communication.
NSContactsUsageDescription
We need to access your contacts to enhance your experience.
NSPhotoLibraryAddUsageDescription
We need permission to add photos to your library.
NSPhotoLibraryUsageDescription
We need full access to your photo library.
NSCalendarsWriteOnlyAccessUsageDescription
We need to create calendar events on your behalf.
NSCalendarsFullAccessUsageDescription
We need full access to your calendar.
NSLocationUsageDescription
We need your location for location-based features.
NSRemindersFullAccessUsageDescription
We need access to your reminders.
NSSpeechRecognitionUsageDescription
We need speech recognition to process audio input.
NSAppleMusicUsageDescription
We need access to your music library.
NSAppleEventsUsageDescription
We need to send Apple Events to other applications.
NSSystemAdministrationUsageDescription
We need full disk access to protect your data.
NSDesktopFolderUsageDescription
We need access to files on your Desktop.
NSDocumentsFolderUsageDescription
We need access to your Documents folder.
NSDownloadsFolderUsageDescription
We need access to your Downloads folder.
PHPhotoLibraryPreventAutomaticLimitedAccessAlert
```
--------------------------------
### Native Function Signature Example (C++)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Provides a glimpse into the native C++ implementation using N-API, showing a function signature for handling calendar access requests.
```cpp
napi_value AskForCalendarAccess(napi_env env, napi_callback_info info) {
// Extract arguments
// Call EventKit API
// Get authorization status
// Convert to JavaScript string
// Resolve or reject Promise
// Return napi_value
}
```
--------------------------------
### N-API Binding Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Demonstrates the structure of an N-API binding for a native function. This snippet outlines the typical steps involved in creating a binding, from argument extraction to returning a JavaScript-compatible value.
```cpp
napi_value GetAuthStatus(napi_env env, napi_callback_info info) {
// Extract arguments from info
// Call native macOS API
// Convert result to JavaScript string
// Return napi_value
}
```
--------------------------------
### Type Checking Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Shows basic type checking for string and boolean parameters.
```javascript
if (typeof targetAppBundleId !== 'string') {
throw new TypeError('targetAppBundleId must be a string')
}
if (typeof shouldPrompt !== 'boolean') {
throw new TypeError('shouldPrompt must be a boolean')
}
```
--------------------------------
### Install Python 3 using Homebrew
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
On macOS 12.3 and newer, Python is not bundled with the system. Install Python 3 using Homebrew to satisfy native module build requirements.
```bash
# Install Python via Homebrew
brew install python3
```
--------------------------------
### Type Validation Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Demonstrates validating a folder parameter against a list of allowed types using Array.includes().
```javascript
const validTypes = ['desktop', 'documents', 'downloads']
if (!validTypes.includes(folder)) {
throw new TypeError(`${folder} is not a valid protected folder`)
}
```
--------------------------------
### Example of Default Parameter with Validation
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/OVERVIEW.md
Demonstrates how default parameters are handled and validated at the JavaScript layer before invoking native code. This pattern ensures robust input handling.
```javascript
function askForCalendarAccess(accessLevel = 'write-only') {
if (!['write-only', 'full'].includes(accessLevel)) {
throw new TypeError(...)
}
return permissions.askForCalendarAccess.call(this, accessLevel)
}
```
--------------------------------
### Request Camera Access in Electron Main Process
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/OVERVIEW.md
Use this snippet in your Electron main process to request camera access. Ensure the 'node-mac-permissions' package is installed.
```javascript
// Electron main process
const { askForCameraAccess } = require('node-mac-permissions')
icpMain.handle('request-camera', async () => {
const status = await askForCameraAccess()
return status === 'authorized'
})
```
--------------------------------
### Promise Rejection Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Demonstrates how asynchronous operations in the native layer result in Promise rejections that can be caught using .catch().
```javascript
askForCameraAccess()
.then(status => { ... })
.catch(error => {
// Handle rejection
})
```
--------------------------------
### Request Access with Fallback and Error Handling
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Attempt to request camera access and handle success or failure. If successful, start the camera; otherwise, show manual instructions or log an error.
```javascript
const { askForCameraAccess } = require('node-mac-permissions')
try {
const status = await askForCameraAccess()
if (status === 'authorized') {
startCamera()
} else {
showManualInstructions()
}
} catch (error) {
console.error('Failed to request camera access:', error.message)
}
```
--------------------------------
### Build Native Module
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
Commands for building, cleaning, and formatting the native Node.js module. Ensure Python is installed for macOS 12.3+.
```bash
# Build the native module
npm run build
```
```bash
# Clean build artifacts
npm run clean
```
```bash
# Format code (C++ and JS)
npm run format
```
--------------------------------
### Check Permissions Status in a CLI Tool
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/OVERVIEW.md
This Node.js CLI example demonstrates how to check the authorization status for camera, microphone, and contacts permissions. It iterates through a list of permissions and logs their status.
```javascript
// Node.js CLI
const { getAuthStatus } = require('node-mac-permissions')
function checkPermissions() {
const perms = ['camera', 'microphone', 'contacts']
perms.forEach(p => {
console.log(`${p}: ${getAuthStatus(p)}`)
})
}
checkPermissions()
```
--------------------------------
### System Preferences Launchers
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Functions that launch System Preferences panes to guide users through granting permissions. These functions do not return a value.
```APIDOC
## askForAccessibilityAccess
### Description
Launches the Accessibility pane in System Preferences to guide the user through granting access.
### Method
Not applicable (JavaScript function)
### Endpoint
Not applicable
### Parameters
None
### Request Example
```javascript
askForAccessibilityAccess();
```
### Response
#### Success Response
This function does not return a value.
#### Response Example
None
```
```APIDOC
## askForFullDiskAccess
### Description
Launches the Full Disk Access pane in System Preferences to guide the user through granting access.
### Method
Not applicable (JavaScript function)
### Endpoint
Not applicable
### Parameters
None
### Request Example
```javascript
askForFullDiskAccess();
```
### Response
#### Success Response
This function does not return a value.
#### Response Example
None
```
```APIDOC
## askForScreenCaptureAccess
### Description
Launches the Screen Recording pane in System Preferences to guide the user through granting access.
### Method
Not applicable (JavaScript function)
### Endpoint
Not applicable
### Parameters
None
### Request Example
```javascript
askForScreenCaptureAccess();
```
### Response
#### Success Response
This function does not return a value.
#### Response Example
None
```
--------------------------------
### Basic Try-Catch for Camera Access
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/errors.md
A fundamental example of using a try-catch block to handle potential errors when requesting camera access. This pattern is applicable to many permission requests.
```javascript
const { askForCameraAccess } = require('node-mac-permissions')
try {
const status = await askForCameraAccess()
console.log(`Camera access: ${status}`)
} catch (error) {
console.error('Failed to request camera access:', error.message)
}
```
--------------------------------
### JavaScript Parameter Validation Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Shows the JavaScript layer's responsibility for validating input parameters, such as checking allowed values for access levels.
```javascript
function askForCalendarAccess(accessLevel = 'write-only') {
if (!['write-only', 'full'].includes(accessLevel)) {
throw new TypeError(`${accessLevel} must be...`)
}
return permissions.askForCalendarAccess.call(this, accessLevel)
}
```
--------------------------------
### Status Conversion Function Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Illustrates helper functions used to convert macOS authorization enums into JavaScript-friendly strings. This snippet shows the definition of string constants and a function signature for converting a photos status.
```cpp
const std::string kAuthorized{"authorized"};
const std::string kDenied{"denied"};
const std::string kRestricted{"restricted"};
const std::string kNotDetermined{"not determined"};
const std::string kLimited{"limited"};
const std::string kProvisional{"provisional"};
const std::string &StringFromPhotosStatus(PHAuthorizationStatus status) {
switch (status) {
case PHAuthorizationStatusAuthorized: return kAuthorized;
case PHAuthorizationStatusDenied: return kDenied;
// ... etc
}
}
```
--------------------------------
### permissions.askForInputMonitoringAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests input monitoring access, allowing the app to 'post' or 'listen' to input events. Available on macOS 10.15+. Returns a Promise resolving to 'authorized' or 'denied'. Guides users to System Preferences if access is denied or not determined. Requires `NSLocationUsageDescription` in `Info.plist`.
```APIDOC
## permissions.askForInputMonitoringAccess([accessLevel])
### Description
Requests access for input monitoring, with options for 'post' or 'listen'. Returns a Promise with the current permission status. Guides users to System Preferences if access is not granted. Requires `NSLocationUsageDescription` in `Info.plist`.
### Method
(Implicitly a function call, not an HTTP method)
### Endpoint
(N/A - SDK method)
### Parameters
#### Path Parameters
(N/A)
#### Query Parameters
(N/A)
#### Request Body
- **accessLevel** (String) - Optional - The access level being requested of Input Monitoring. Can be either `post` or `listen`. Default is `listen`. Only available on macOS 10.15 or higher.
### Request Example
```js
const { askForInputMonitoringAccess } = require('node-mac-permissions')
askForInputMonitoringAccess().then(status => {
console.log(`Access to Input Monitoring is ${status}`)
})
```
### Response
#### Success Response
- **status** (String) - Current permission status; can be `authorized` or `denied`.
#### Response Example
(See Request Example)
```
--------------------------------
### permissions.askForLocationAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests location access. This method is only available on macOS 10.15 or higher. It can prompt the user to grant 'always' or 'when-in-use' access. If access is denied or not determined, it guides the user to System Preferences. An NSLocationUsageDescription key in Info.plist is required.
```APIDOC
## permissions.askForLocationAccess([accessLevel])
### Description
Requests location access, with options for 'always' or 'when-in-use' levels. Guides users to System Preferences if access is not granted. Requires `NSLocationUsageDescription` in `Info.plist`.
### Method
(Implicitly a function call, not an HTTP method)
### Endpoint
(N/A - SDK method)
### Parameters
#### Path Parameters
(N/A)
#### Query Parameters
(N/A)
#### Request Body
- **accessLevel** (String) - Optional - The access level being requested of Location. Can be either `always` or `when-in-use`. Default is `when-in-use`. Only available on macOS 10.15 or higher.
### Request Example
(N/A - SDK method)
### Response
#### Success Response
(void - function does not return a value)
#### Response Example
(N/A - void return)
```
--------------------------------
### Module Loading Sequence
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Illustrates the step-by-step process of loading and initializing the node-mac-permissions module, from requiring the module to making native calls.
```javascript
// 1. Load the module
const permissions = require('node-mac-permissions')
// 2. index.js executes
// a. Loads native binding via bindings()
const nativeBinding = require('bindings')('permissions.node')
// b. Wraps functions with parameter validation
// c. Exports wrapper functions
module.exports = { ... }
// 3. Native binding executes (permissions.mm)
// a. Module initialization function runs
// b. All N-API functions are registered
// c. Native functions available to JavaScript
// 4. User can call functions
const status = permissions.getAuthStatus('camera')
```
--------------------------------
### TypeScript Function Signature Example (Restricted)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Example of a TypeScript function signature for a permission that can be system-restricted, returning PermissionType.
```typescript
// Can be restricted (camera/microphone/music)
export function askForCameraAccess(): Promise
```
--------------------------------
### askForScreenCaptureAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Opens System Preferences to the Screen Capture settings. Returns undefined.
```APIDOC
## askForScreenCaptureAccess(openPreferences?: boolean)
### Description
Opens System Preferences to the Screen Capture settings. The `openPreferences` parameter defaults to `false`.
### Parameters
#### Path Parameters
- **openPreferences** (boolean) - Optional - Whether to open the System Preferences pane. Defaults to `false`.
### Response
#### Success Response
- **undefined** - This function does not return a value.
```
--------------------------------
### TypeScript Function Signature Example (Not Restricted)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Example of a TypeScript function signature for a permission that cannot be system-restricted, returning Omit.
```typescript
// Cannot be restricted (calendar/contacts/folders)
export function askForCalendarAccess(
accessType?: 'write-only' | 'full'
): Promise>
```
--------------------------------
### index.js Entry Point Structure
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Illustrates the typical structure of the main JavaScript entry point, including loading native bindings, defining validation functions, and exporting wrappers.
```javascript
// 1. Load native binding (line 1)
const permissions = require('bindings')('permissions.node')
// 2. Define validation functions (lines 3-93)
function getAuthStatus(type) { ... }
function askForFoldersAccess(folder) { ... }
function askForCalendarAccess(accessLevel) { ... }
// ... more wrapper functions
// 3. Export wrapper functions (lines 95-114)
module.exports = {
askForAppleEventsAccess: askForAppleEventsAccess,
askForAccessibilityAccess: permissions.askForAccessibilityAccess,
// ... other exports
}
```
--------------------------------
### Handling Invalid Folder in askForFoldersAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/errors.md
Example of calling askForFoldersAccess with an invalid folder name and catching the TypeError.
```javascript
const { askForFoldersAccess } = require('node-mac-permissions')
try {
askForFoldersAccess('home')
} catch (error) {
// Error: home is not a valid protected folder
console.error(error.message)
}
```
--------------------------------
### askForFullDiskAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Opens System Preferences to the Full Disk Access settings. No programmatic API is available to grant access directly.
```APIDOC
## askForFullDiskAccess()
### Description
Opens System Preferences to the Full Disk Access settings. Note: There is no programmatic API available to grant access directly.
### Response
#### Success Response
- **undefined** - This function does not return a value.
```
--------------------------------
### Handling Invalid Type in getAuthStatus
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/errors.md
Example of calling getAuthStatus with an invalid type and catching the resulting TypeError.
```javascript
const { getAuthStatus } = require('node-mac-permissions')
try {
const status = getAuthStatus('invalid')
} catch (error) {
// Error: invalid is not a valid type
console.error(error.message)
}
```
--------------------------------
### Configure Electron Sandbox
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
Enable the sandbox in your Electron main process configuration. Ensure all necessary Info.plist usage descriptions are present when sandboxing is enabled.
```javascript
// In your Electron main process
const win = new BrowserWindow({
webPreferences: {
sandbox: true, // Enable sandbox
// Other preferences...
}
})
```
--------------------------------
### JavaScript Error Handling Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Shows how TypeErrors are caught when invalid parameters are passed to functions in the JavaScript layer.
```javascript
try {
getAuthStatus('invalid')
} catch (error) {
// TypeError: invalid is not a valid type
// Stack: thrown in index.js line 26-28
}
```
--------------------------------
### Dynamic Binding with 'bindings' Package
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Demonstrates how the 'bindings' package is used to automatically locate and load the compiled native binary (.node file) for the module.
```javascript
const binding = require('bindings')('permissions.node')
```
--------------------------------
### permissions.askForScreenCaptureAccess([openPreferences])
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to capture the screen. An optional parameter can be provided to open preferences.
```APIDOC
## permissions.askForScreenCaptureAccess([openPreferences])
### Description
Requests access to capture the screen.
### Method
`askForScreenCaptureAccess([openPreferences])`
### Endpoint
N/A (SDK method)
### Parameters
#### Query Parameters
- **openPreferences** (Boolean) - Optional - If true, opens the system preferences to the screen capture section.
```
--------------------------------
### Handling Invalid Access Level in askForLocationAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/errors.md
Example of calling askForLocationAccess with an invalid access level and catching the TypeError.
```javascript
const { askForLocationAccess } = require('node-mac-permissions')
try {
askForLocationAccess('background')
} catch (error) {
// Error: background must be one of either 'when-in-use' or 'always'
console.error(error.message)
}
```
--------------------------------
### askForAccessibilityAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Opens System Preferences to the Accessibility settings. No programmatic API is available to grant access directly.
```APIDOC
## askForAccessibilityAccess()
### Description
Opens System Preferences to the Accessibility settings. Note: There is no programmatic API available to grant access directly.
### Response
#### Success Response
- **undefined** - This function does not return a value.
```
--------------------------------
### Get Authorization Status
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Checks the current authorization status for a specified macOS system component. Use this to determine if your application has permission before attempting an action.
```javascript
const { getAuthStatus } = require('node-mac-permissions')
// Check if app has camera access
const status = getAuthStatus('camera')
if (status === 'authorized') {
console.log('Camera access granted')
} else if (status === 'denied') {
console.log('Camera access denied')
} else if (status === 'not determined') {
console.log('User has not decided yet')
}
// Check multiple types
const types = ['camera', 'microphone', 'contacts']
for (const type of types) {
console.log(`${type}: ${getAuthStatus(type)}`)
}
```
--------------------------------
### permissions.askForCameraAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Checks the authorization status for camera access. Prompts the user if the status is 'not determined'. Opens System Preferences if status is 'denied'.
```APIDOC
## permissions.askForCameraAccess()
### Description
Checks the authorization status for camera access. If the status is 'not determined', it prompts the user to authorize or deny. If the status is 'denied', the `Security & Privacy` System Preferences window is opened with the Camera privacy key highlighted. The Promise resolves with 'authorized', 'denied', or 'restricted'. Your app must provide an explanation for camera use in `Info.plist` using the `NSCameraUsageDescription` key.
### Method
`askForCameraAccess()`
### Returns
`Promise` - 'authorized', 'denied', or 'restricted'.
### Example
```js
const { askForCameraAccess } = require('node-mac-permissions')
askForCameraAccess().then(status => {
console.log(`Access to Camera is ${status}`)
})
```
### Info.plist Configuration
```plist
NSCameraUsageDescription
Your reason for wanting to access the Camera
```
```
--------------------------------
### permissions.askForFullDiskAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests full disk access for the application, granting it broad permissions to read and write files across the system.
```APIDOC
## permissions.askForFullDiskAccess()
### Description
Requests full disk access for the application.
### Method
`askForFullDiskAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### Add Music Library Usage Description to Info.plist
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
This Info.plist key is required to explain the need for accessing the user's music library. It must be present before calling music library permission functions.
```plist
NSAppleMusicUsageDescription
Your reason for wanting to access the user’s media library.
```
--------------------------------
### Get Application Bundle Identifier
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
Retrieve the bundle identifier for any macOS application using the mdls command-line tool. This is useful for targeting specific apps with permission checks.
```bash
mdls -name kMDItemCFBundleIdentifier -r /Applications/MyApp.app
```
--------------------------------
### Check Authorization Status for Multiple macOS Permissions
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Iterates through a list of permission types and logs their current authorization status. Ensure you have the 'node-mac-permissions' module installed and imported as 'getAuthStatus'.
```javascript
const types = [
'accessibility',
'bluetooth',
'calendar',
'camera',
'contacts',
'external-storage',
'focus-status',
'full-disk-access',
'input-monitoring',
'location',
'microphone',
'music-library',
'notifications',
'photos-add-only',
'photos-read-write',
'reminders',
'speech-recognition',
'screen',
]
for (const type of types) {
const status = getAuthStatus(type)
console.log(`Access to ${type} is ${status}`)
}
```
--------------------------------
### askForFullDiskAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Requests full disk access. This is a direct native call and returns undefined.
```APIDOC
## askForFullDiskAccess
### Description
Requests full disk access. This is a direct native call and returns undefined.
### Method
N/A (Asynchronous JavaScript function)
### Parameters
(none)
### Return
- **undefined**
```
--------------------------------
### askForScreenCaptureAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Requests screen capture permission on macOS. If denied and `openPreferences` is true, it will open System Preferences to the Screen Capture pane. Note that this function does not return a Promise.
```APIDOC
## askForScreenCaptureAccess
### Description
Requests screen capture permission on macOS. If denied and `openPreferences` is true, it will open System Preferences to the Screen Capture pane. Note that this function does not return a Promise.
### Method
Not applicable (SDK function)
### Parameters
#### Query Parameters
- **openPreferences** (boolean) - Optional - If true, opens System Preferences to the Screen Capture pane upon denial.
### Request Example
```javascript
const { askForScreenCaptureAccess } = require('node-mac-permissions')
// Request screen capture permission
askForScreenCaptureAccess()
// Request with automatic System Preferences fallback
askForScreenCaptureAccess(true)
```
### Response
This function does not return a Promise. Its effect is to trigger a system permission modal or open System Preferences.
```
--------------------------------
### askForCameraAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access to the user's camera. Returns a Promise that resolves to a string status.
```APIDOC
## askForCameraAccess()
### Description
Requests access to the user's camera.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied', 'restricted').
```
--------------------------------
### askForScreenCaptureAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Requests permission for the application to capture the screen. This function does not return a Promise.
```APIDOC
## askForScreenCaptureAccess
### Description
Requests permission for the application to capture the screen. This function does not return a Promise; permission is handled asynchronously by the system.
### Method
`askForScreenCaptureAccess(openPreferences?: boolean): undefined`
### Parameters
#### Query Parameters
- **openPreferences** (boolean) - Optional - If `true` and the permission request is denied or fails, automatically open System Preferences to the Screen Capture pane.
### Return Value
Returns `undefined`.
### Throws
- **TypeError**: Thrown when `openPreferences` is not a boolean.
```
--------------------------------
### Check Authorization Status
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Use this function to get the current authorization status for a given permission type. The status indicates whether access is granted, denied, restricted, or not yet determined.
```typescript
getAuthStatus(type: AuthType): string
```
--------------------------------
### Type Narrowing Example
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Demonstrates how TypeScript's type system prevents checking for 'restricted' status when a function is guaranteed to return a type that omits it. This ensures type safety at compile time.
```typescript
const status = await askForCalendarAccess() // 'authorized' | 'denied'
// Type system prevents checking for 'restricted'
```
--------------------------------
### askForInputMonitoringAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access for input monitoring (keyboard/mouse events). Returns a Promise that resolves to a string status.
```APIDOC
## askForInputMonitoringAccess(accessLevel?: 'listen' | 'post')
### Description
Requests access for input monitoring. The `accessLevel` parameter defaults to `'listen'` (macOS 10.15+).
### Parameters
#### Path Parameters
- **accessLevel** ('listen' | 'post') - Optional - The level of input monitoring access. Defaults to `'listen'`.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied').
```
--------------------------------
### Check Apple Events Access for Apps
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/configuration.md
Use askForAppleEventsAccess with bundle identifiers to check permissions for specific macOS applications. This example iterates through common bundle IDs and logs their access status.
```javascript
const { askForAppleEventsAccess } = require('node-mac-permissions')
// Common bundle identifiers
const bundleIds = {
'Finder': 'com.apple.finder',
'Mail': 'com.apple.mail',
'Safari': 'com.apple.Safari',
'System Events': 'com.apple.systemevents',
'Script Editor': 'com.apple.ScriptEditor2',
}
for (const [name, bundleId] of Object.entries(bundleIds)) {
askForAppleEventsAccess(bundleId).then(status => {
console.log(`${name}: ${status}`)
})
}
```
--------------------------------
### permissions.askForMusicLibraryAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to the user's music library. Prompts the user for authorization. Returns a Promise resolving to 'authorized', 'denied', or 'restricted'. If denied or not determined, it opens the relevant System Preferences pane. Requires `NSAppleMusicUsageDescription` in `Info.plist`.
```APIDOC
## permissions.askForMusicLibraryAccess()
### Description
Requests access to the user's music library, prompting for authorization. Returns a Promise with the current permission status. Guides users to System Preferences if access is denied. Requires `NSAppleMusicUsageDescription` in `Info.plist`.
### Method
(Implicitly a function call, not an HTTP method)
### Endpoint
(N/A - SDK method)
### Parameters
#### Path Parameters
(N/A)
#### Query Parameters
(N/A)
#### Request Body
(N/A)
### Request Example
```js
const { askForMusicLibraryAccess } = require('node-mac-permissions')
askForMusicLibraryAccess().then(status => {
console.log(`Access to Apple Music Library is ${status}`)
})
```
### Response
#### Success Response
- **status** (String) - Whether or not the request succeeded or failed; can be `authorized`, `denied`, or `restricted`.
#### Response Example
(See Request Example)
```
--------------------------------
### permissions.askForFoldersAccess(folder)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to a specified folder ('desktop', 'documents', or 'downloads'). Returns a Promise that resolves with 'authorized' or 'denied'.
```APIDOC
## permissions.askForFoldersAccess(folder)
### Description
Requests access to a specified folder. The `folder` parameter can be one of 'desktop', 'documents', or 'downloads'. The Promise resolves with 'authorized' or 'denied'. Ensure the corresponding `Info.plist` key is set for usage description.
### Method
`askForFoldersAccess(folder: String)`
### Parameters
#### Path Parameters
- **folder** (String) - Required - The folder to which you are requesting access. Can be one of `desktop`, `documents`, or `downloads`.
### Returns
`Promise` - 'authorized' or 'denied'.
### Example
```js
const { askForFoldersAccess } = require('node-mac-permissions')
askForFoldersAccess('desktop').then(status => {
console.log(`Access to Desktop is ${status}`)
})
```
### Info.plist Configuration
```plist
NSDesktopFolderUsageDescription
Your reason for wanting to access the Desktop folder
```
```plist
NSDocumentsFolderUsageDescription
Your reason for wanting to access the Documents folder
```
```plist
NSDownloadsFolderUsageDescription
Your reason for wanting to access the Downloads folder
```
```
--------------------------------
### Import Permissions with TypeScript
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Import permission functions and types with TypeScript. Demonstrates checking camera access status and type.
```typescript
import {
getAuthStatus,
askForCameraAccess,
AuthType,
PermissionType,
} from 'node-mac-permissions'
const status: PermissionType = await askForCameraAccess()
const authType: AuthType = 'camera'
```
--------------------------------
### permissions.askForCameraAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to the device's camera.
```APIDOC
## permissions.askForCameraAccess()
### Description
Requests access to the device's camera.
### Method
`askForCameraAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### askForFoldersAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access to specific user folders (desktop, documents, downloads). Returns a Promise that resolves to a string status.
```APIDOC
## askForFoldersAccess(folder: 'desktop' | 'documents' | 'downloads')
### Description
Requests access to specific user folders.
### Parameters
#### Path Parameters
- **folder** ('desktop' | 'documents' | 'downloads') - Required - The folder to request access for.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied').
```
--------------------------------
### Node Mac Permissions File Organization
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Overview of the directory and file structure for the node-mac-permissions project.
```tree
node-mac-permissions/
├── index.js # Main entry point (113 lines)
├── index.d.ts # TypeScript definitions (43 lines)
├── permissions.mm # Native implementation (~1200+ lines)
├── binding.gyp # Node-gyp configuration
├── package.json # Package metadata
├── README.md # Documentation
├── test/
│ └── module.spec.js # Test suite (97 tests)
└── build/ # Compiled output (generated)
└── Release/
└── permissions.node # Native binary
```
--------------------------------
### permissions.askForMicrophoneAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests microphone access. Prompts the user to authorize or deny. Returns a Promise resolving to 'authorized', 'denied', or 'restricted'. If denied or not determined, it opens the relevant System Preferences pane. Requires `NSMicrophoneUsageDescription` in `Info.plist`.
```APIDOC
## permissions.askForMicrophoneAccess()
### Description
Requests microphone access, prompting the user for authorization. Returns a Promise with the current permission status. Guides users to System Preferences if access is denied. Requires `NSMicrophoneUsageDescription` in `Info.plist`.
### Method
(Implicitly a function call, not an HTTP method)
### Endpoint
(N/A - SDK method)
### Parameters
#### Path Parameters
(N/A)
#### Query Parameters
(N/A)
#### Request Body
(N/A)
### Request Example
```js
const { askForMicrophoneAccess } = require('node-mac-permissions')
askForMicrophoneAccess().then(status => {
console.log(`Access to Microphone is ${status}`)
})
```
### Response
#### Success Response
- **status** (String) - Current permission status; can be `authorized`, `denied`, or `restricted`.
#### Response Example
(See Request Example)
```
--------------------------------
### permissions.askForMusicLibraryAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to the user's music library.
```APIDOC
## permissions.askForMusicLibraryAccess()
### Description
Requests access to the user's music library.
### Method
`askForMusicLibraryAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### Request Folder Access (Desktop)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Prompts the user to authorize or deny access to the Desktop folder. The promise resolves with 'authorized' or 'denied'.
```javascript
const { askForFoldersAccess } = require('node-mac-permissions')
askForFoldersAccess('desktop').then(status => {
console.log(`Access to Desktop is ${status}`)
})
```
```plist
NSDesktopFolderUsageDescription
Your reason for wanting to access the Desktop folder
```
--------------------------------
### Request Folder Access (Downloads)
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Prompts the user to authorize or deny access to the Downloads folder. The promise resolves with 'authorized' or 'denied'.
```plist
NSDownloadsFolderUsageDescription
Your reason for wanting to access the Downloads folder
```
--------------------------------
### Open Full Disk Access Preferences
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Opens System Preferences to the Full Disk Access pane. This function does not return a Promise and requires manual user interaction to grant access. Your app's Info.plist should include NSSystemAdministrationUsageDescription.
```javascript
const { askForFullDiskAccess } = require('node-mac-permissions')
askForFullDiskAccess()
// Opens System Preferences to Full Disk Access pane
```
--------------------------------
### Request Screen Capture Access
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Use this function to request screen capture permission. If denied and `openPreferences` is set to `true`, System Preferences will open to the Screen Capture pane.
```javascript
const { askForScreenCaptureAccess } = require('node-mac-permissions')
// Request screen capture permission
askForScreenCaptureAccess()
// Request with automatic System Preferences fallback
askForScreenCaptureAccess(true)
```
--------------------------------
### Open Full Disk Access System Preferences
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Opens the Full Disk Access section in System Preferences. This permission must be granted manually by the user.
```typescript
askForFullDiskAccess(): undefined
```
--------------------------------
### Importing All Permissions Functions
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/OVERVIEW.md
Demonstrates how to import all exported functions from the node-mac-permissions library using a single require statement. This is a common pattern for accessing the library's full API.
```javascript
const permissions = require('node-mac-permissions')
const {
getAuthStatus,
askForCameraAccess,
askForMicrophoneAccess,
// ... other functions
} = require('node-mac-permissions')
```
--------------------------------
### Add Microphone Usage Description to Info.plist
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Add this key to your app's Info.plist to explain why microphone access is needed. This is a prerequisite for using microphone permission APIs.
```plist
NSMicrophoneUsageDescription
Your reason for wanting to access the Microphone
```
--------------------------------
### Fire-and-Forget for System Preferences Launchers
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Functions that launch System Preferences do not return a value. They execute and open the relevant pane without providing a status or result.
```javascript
askForFullDiskAccess()
// No return value; opens System Preferences
```
--------------------------------
### permissions.askForInputMonitoringAccess([accessLevel])
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to monitor user input events. An optional access level can be specified.
```APIDOC
## permissions.askForInputMonitoringAccess([accessLevel])
### Description
Requests access to monitor user input events.
### Method
`askForInputMonitoringAccess([accessLevel])`
### Endpoint
N/A (SDK method)
### Parameters
#### Query Parameters
- **accessLevel** (String) - Optional - Specifies the level of input monitoring access requested.
```
--------------------------------
### permissions.askForSpeechRecognitionAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to the speech recognition capabilities of the system.
```APIDOC
## permissions.askForSpeechRecognitionAccess()
### Description
Requests access to the speech recognition capabilities of the system.
### Method
`askForSpeechRecognitionAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### askForScreenCaptureAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Requests screen capture access. This is an asynchronous operation that returns undefined.
```APIDOC
## askForScreenCaptureAccess
### Description
Requests screen capture access. This is an asynchronous operation that returns undefined.
### Method
N/A (Asynchronous JavaScript function)
### Parameters
#### Query Parameters
- **openPreferences** (boolean) - Optional - Whether to open system preferences.
### Return
- **undefined**
```
--------------------------------
### permissions.askForMicrophoneAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to the device's microphone.
```APIDOC
## permissions.askForMicrophoneAccess()
### Description
Requests access to the device's microphone.
### Method
`askForMicrophoneAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### permissions.askForExternalStorageAccess()
Source: https://github.com/codebytere/node-mac-permissions/blob/main/README.md
Requests access to external storage devices.
```APIDOC
## permissions.askForExternalStorageAccess()
### Description
Requests access to external storage devices.
### Method
`askForExternalStorageAccess()`
### Endpoint
N/A (SDK method)
### Parameters
None
```
--------------------------------
### askForMicrophoneAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access to the user's microphone. Returns a Promise that resolves to a string status.
```APIDOC
## askForMicrophoneAccess()
### Description
Requests access to the user's microphone.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied', 'restricted').
```
--------------------------------
### askForCameraAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Requests permission for the application to access the camera device. Handles different authorization statuses.
```APIDOC
## askForCameraAccess
### Description
Requests permission for the application to access the camera device. Handles different authorization statuses.
### Method
```js
askForCameraAccess(): Promise
```
### Parameters
None.
### Return Value
Returns a Promise that resolves to a string:
- `authorized` - Camera access was granted or is already granted.
- `denied` - Camera access was denied by the user.
- `restricted` - Camera access is restricted (e.g., by parental controls).
### Requirements
Your app's `Info.plist` must include:
```plist
NSCameraUsageDescription
Explanation of why your app needs to access the camera
```
### Behavior
- If authorization status is `not determined`, the system prompts the user to authorize or deny access. The Promise resolves with their choice.
- If authorization is already `denied`, the System Preferences window opens to the Camera privacy pane, and the Promise resolves as `denied`.
- If authorization is `restricted`, the Promise resolves as `restricted`.
### Example
```js
const { askForCameraAccess } = require('node-mac-permissions')
askForCameraAccess().then(status => {
if (status === 'authorized') {
console.log('Camera access granted, can start video')
} else if (status === 'denied') {
console.log('Camera access denied')
} else if (status === 'restricted') {
console.log('Camera access is restricted')
}
})
```
```
--------------------------------
### Check Status Then Request Access
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Check the current authorization status for camera access and request it if not determined. Logs the result or current status.
```javascript
const { getAuthStatus, askForCameraAccess } = require('node-mac-permissions')
const status = getAuthStatus('camera')
if (status === 'not determined') {
const result = await askForCameraAccess()
console.log(`Camera access: ${result}`)
} else if (status === 'authorized') {
console.log('Camera already authorized')
} else {
console.log('Camera access denied or restricted')
}
```
--------------------------------
### askForAccessibilityAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Requests accessibility access. This is a direct native call and returns undefined.
```APIDOC
## askForAccessibilityAccess
### Description
Requests accessibility access. This is a direct native call and returns undefined.
### Method
N/A (Asynchronous JavaScript function)
### Parameters
(none)
### Return
- **undefined**
```
--------------------------------
### askForPhotosAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access to the user's photos. Returns a Promise that resolves to a string status.
```APIDOC
## askForPhotosAccess(accessLevel?: 'add-only' | 'read-write')
### Description
Requests access to the user's photos. The `accessLevel` parameter defaults to `'add-only'` (macOS 11+).
### Parameters
#### Path Parameters
- **accessLevel** ('add-only' | 'read-write') - Optional - The level of photos access. Defaults to `'add-only'`.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied', 'restricted').
```
--------------------------------
### Open Screen Capture System Preferences
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Opens the Screen Capture settings in System Preferences. You can optionally control whether the preferences pane is opened. Defaults to not opening.
```typescript
askForScreenCaptureAccess(openPreferences?: boolean): undefined
```
--------------------------------
### askForMicrophoneAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Requests permission for the application to access the microphone. This is crucial for any application that needs to record audio.
```APIDOC
## askForMicrophoneAccess
Requests permission for the application to access the microphone device.
```js
askForMicrophoneAccess(): Promise
```
### Parameters
None.
### Return Value
Returns a Promise that resolves to a string:
- `authorized` - Microphone access was granted or is already granted.
- `denied` - Microphone access was denied by the user.
- `restricted` - Microphone access is restricted (e.g., by parental controls).
### Requirements
Your app's `Info.plist` must include:
```plist
NSMicrophoneUsageDescription
Explanation of why your app needs to access the microphone
```
### Behavior
- If authorization status is `not determined`, the system prompts the user. The Promise resolves with their choice.
- If authorization is already `denied`, the System Preferences window opens to the Microphone privacy pane, and the Promise resolves as `denied`.
- If authorization is `restricted`, the Promise resolves as `restricted`.
### Example
```js
const { askForMicrophoneAccess } = require('node-mac-permissions')
askForMicrophoneAccess().then(status => {
if (status === 'authorized') {
console.log('Microphone access granted')
} else if (status === 'denied') {
console.log('Microphone access denied')
}
})
```
```
--------------------------------
### askForMusicLibraryAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/QUICK_REFERENCE.md
Requests access to the user's music library. Returns a Promise that resolves to a string status.
```APIDOC
## askForMusicLibraryAccess()
### Description
Requests access to the user's music library.
### Response
#### Success Response
- **status** (string) - The authorization status (e.g., 'authorized', 'denied', 'restricted').
```
--------------------------------
### Native Implementation High-Level Structure
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/MODULE_STRUCTURE.md
Outlines the key components of the Objective-C++ native implementation, including N-API headers, framework imports, helper functions, N-API wrapper functions, and module initialization.
```objective-c++
#include // Node.js N-API header
#import <...> // macOS framework imports (20+ frameworks)
/***** HELPER FUNCTIONS *****/
// Status string conversion functions
// File access checking
// URL resolution helpers
// Permission dialog detection
/***** NAPI WRAPPER FUNCTIONS *****/
// getAuthStatus(type) binding
// askForCameraAccess() binding
// askForMicrophoneAccess() binding
// ... other bindings
/***** MODULE INITIALIZATION *****/
napi_value Init(napi_env env, napi_value exports) {
// Register all functions
napi_set_named_property(env, exports, "getAuthStatus", ...)
// ... register other functions
return exports
}
```
--------------------------------
### askForFoldersAccess
Source: https://github.com/codebytere/node-mac-permissions/blob/main/_autodocs/api-reference/permissions.md
Requests permission for the application to access a protected user folder. Valid folders are 'desktop', 'documents', or 'downloads'.
```APIDOC
## askForFoldersAccess
### Description
Requests permission for the application to access a protected user folder.
### Method Signature
```js
askForFoldersAccess(folder: string): Promise
```
### Parameters
#### Path Parameters
- **folder** (string) - Required - The folder to access. Must be one of: `desktop`, `documents`, or `downloads`.
### Return Value
Returns a Promise that resolves to a string indicating the authorization status:
- `authorized`: Folder access was granted or is already granted.
- `denied`: Folder access was denied by the user.
### Throws
- **TypeError**: Thrown when `folder` is not one of the valid protected folder types.
### Requirements
Your app's `Info.plist` must include the appropriate usage description keys for the requested folder (e.g., `NSDesktopFolderUsageDescription`, `NSDocumentsFolderUsageDescription`, `NSDownloadsFolderUsageDescription`).
### Example
```js
const { askForFoldersAccess } = require('node-mac-permissions')
// Request Desktop folder access
askForFoldersAccess('desktop').then(status => {
console.log(`Desktop access: ${status}`)
})
// Request Documents folder access
askForFoldersAccess('documents').then(status => {
console.log(`Documents access: ${status}`)
})
// Request Downloads folder access
askForFoldersAccess('downloads').then(status => {
console.log(`Downloads access: ${status}`)
})
```
```