Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
Corentin Mors committed Apr 3, 2024
0 parents commit 6c28947
Show file tree
Hide file tree
Showing 17 changed files with 5,561 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"prettier",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"project": "tsconfig.json"
},
"env": {
"node": true,
"es6": true
},
"rules": {
"require-await": "error",
"no-return-await": "error",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"varsIgnorePattern": "[iI]gnored",
"argsIgnorePattern": "^_"
}
],
"object-shorthand": ["error", "always"]
},
"globals": {}
}
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: [mikescops]
30 changes: 30 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: Mikescops
---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:

1. xxx
2. yyy
3. zzz

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Environment (please complete the following information):**

- Node Version [e.g. 22]

**Additional context**
Add any other context about the problem here.
19 changes: 19 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: Mikescops
---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
25 changes: 25 additions & 0 deletions .github/workflows/pr-validation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Lint & Build CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
build:
runs-on: macos-14 # ARM64

steps:
- uses: actions/checkout@v2
- name: Use Node.js 18.20.x
uses: actions/setup-node@v1
with:
node-version: 18.20.x
- name: Use Swift 5.9
uses: swift-actions/setup-swift@v2
with:
swift-version: 5.9
- run: npm ci
- run: npm run lint
- run: npm run build
24 changes: 24 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Publish Package to npmjs

on:
release:
types: [created]

jobs:
build:
runs-on: macos-14
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18.20.x
registry-url: 'https://registry.npmjs.org'
- name: Use Swift 5.9
uses: swift-actions/setup-swift@v2
with:
swift-version: 5.9
- run: npm ci && npm run build
- name: Publish package on NPM 📦
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.build
.parcel-cache
dist
node_modules
.vscode
KeychainLibrary
package/
11 changes: 11 additions & 0 deletions .parcelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "@parcel/config-default",
"transformers": {
"*.{ts}": [
"@parcel/transformer-typescript-tsc"
]
},
"reporters": [
"parcel-reporter-static-files-copy"
]
}
7 changes: 7 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"singleQuote": true,
"printWidth": 120,
"tabWidth": 4,
"arrowParens": "always",
"trailingComma": "none"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2023 Corentin Mors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
19 changes: 19 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// swift-tools-version: 5.9

import PackageDescription

let package = Package(
name: "KeychainLibrary",
products: [
.library(
name: "KeychainLibrary",
type: .dynamic,
targets: ["KeychainLibrary"]),
],
targets: [
.target(
name: "KeychainLibrary",
dependencies: [])
]
)

133 changes: 133 additions & 0 deletions Sources/KeychainLibrary.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation
import LocalAuthentication
import Security

// Function to add data to keychain with biometrics protection
@_cdecl("addToKeychain")
public func addToKeychain(cStringData: UnsafePointer<Int8>, cStringService: UnsafePointer<Int8>) -> Bool {
let data = String(cString: cStringData).data(using: .utf8)!
let service = String(cString: cStringService)

if #available(macOS 10.13.4, *) {
let context = LAContext()

var error: NSError?
guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
print("Biometric authentication not available: \(error?.localizedDescription ?? "Unknown error")")
return false
}

let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecValueData as String: data,
kSecUseAuthenticationContext as String: context
]

// Delete existing item if exists
SecItemDelete(query as CFDictionary)

let status = SecItemAdd(query as CFDictionary, nil)
// print(SecCopyErrorMessageString(status, nil)!)

return status == errSecSuccess
}

return false
}

// Function to retrieve data from keychain with biometrics protection
@_cdecl("getFromKeychain")
public func getFromKeychain(
cStringService: UnsafePointer<Int8>,
requireBiometrics: Bool,
callback: @escaping @convention(c) (UnsafePointer<Int8>?, UnsafePointer<Int8>?
) -> Void) {
let semaphore = DispatchSemaphore(value: 0)

var resultData: String?
var resultError: Error?

do {
let service = String(cString: cStringService)
try _getFromKeychain(service: service, requireBiometrics: requireBiometrics) { result in
switch result {
case .success(let data):
resultData = data
case .failure(let error):
resultError = error
}
semaphore.signal()
}
} catch {
resultError = error
semaphore.signal()
}

semaphore.wait()

if let data = resultData {
return callback(nil, data)
}

callback(resultError?.localizedDescription, nil)
}

enum BiometricAuthenticationError: Error {
case notAvailable(String)
case failed(String)
case cannotRetrieve(String)
case unknown(String)
}

func _getFromKeychain(service: String, requireBiometrics: Bool, completion: @escaping (Result<String, BiometricAuthenticationError>) -> Void) throws {
let context = LAContext()

// Check if biometric authentication is available
var error: NSError?
guard !requireBiometrics || context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
completion(.failure(.notAvailable("Biometric authentication not available: \(error?.localizedDescription ?? "Unknown error")")))
return
}

// Check biometric authentication
let policy: LAPolicy = .deviceOwnerAuthenticationWithBiometrics

if requireBiometrics {
context.evaluatePolicy(policy, localizedReason: "Access to your secret") { success, evaluateError in
if success {
_getPassword(context: context, service: service, completion: completion)
} else {
if let error = evaluateError {
completion(.failure(.failed("Biometric authentication failed: \(error.localizedDescription)")))
} else {
completion(.failure(.failed("Biometric authentication failed")))
}
}
}
} else {
_getPassword(context: context, service: service, completion: completion)
}
}

func _getPassword(context: LAContext, service: String, completion: @escaping (Result<String, BiometricAuthenticationError>) -> Void) {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecUseAuthenticationContext as String: context,
kSecReturnData as String: true
]

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

if status == errSecSuccess, let data = result as? Data {
if let dataString = String(data: data, encoding: .utf8) {
completion(.success(dataString))
} else {
completion(.failure(.cannotRetrieve("Failed to retrieve data from keychain")))
}
} else {
completion(.failure(.cannotRetrieve("Failed to retrieve data from keychain")))
}
}
Loading

0 comments on commit 6c28947

Please sign in to comment.