1password 中文文档教程

发布于 7年前 浏览 44 项目主页 更新于 3年前

Cloud Keychain for Node.js (v0.2.1)

这是一个小型图书馆,可以轻松使用 1Password 的 .cloudKeychain 文件。

这个实现是基于 官方 Agile Bits 文档 还有 python 库 OnePasswordPy

重要说明:我不以任何方式隶属于 AgileBits,制造商 1 个密码。 他们的软件很棒,你应该去买。

目前支持:

  • Unlock keychain using Master Password
  • Load items from band_*.js files
  • Unlock item overview, keys and details
  • Create keychains and items

待办事项:

  • Find out how to calcuate the HMAC of items correctly
  • Actually do something with item data (instead of just handing back the raw JSON)
  • Get syncing working.
  • Add memoize pattern to opdata class to speed up item locking when no data has changed.

Installation

npm install 1password

How to Use

第一步:打开钥匙串

Keychain = require( '1password' );
keychain = new Keychain();
keychain.load( './1password.cloudkeychain', function( err ) {
    console.log( 'Keychain has loaded' ); 
});

第二步:解锁钥匙串

keychain.unlock( 'password' );

if ( keychain.unlocked ) {
    console.log( 'Successfully unlocked keychain' );
} else {
    console.log( 'Error: Could not unlock keychain' );
}

第三步:获取物品

keychain.eachItem( function( item ) {
  console.log( item );
});

第四步:解密项目详细信息

item = keychain.findItems( 'Facebook' )[0];
item.unlockDetails();
console.log( item.details );

Main Keychain Methods

Keychain.create(password, settings)

返回使用指定密码加密的空钥匙串。

keychain = Keychain.create( 'password', {
    passwordHint: 'hint'
});
profile = keychain.exportProfile();
console.log( profile );

settings 参数是一个对象,可以覆盖任何默认值 值。 但是不能添加额外的设置。 默认设置是:

settings = {
  uuid: Crypto.generateUuid(),
  salt: Crypto.randomBytes(16),
  createdAt: currentTime,
  updatedAt: currentTime,
  iterations: 10000,
  profileName: 'default',
  passwordHint: '',
  lastUpdatedBy: 'Dropbox'
};

这记录了以下内容(为了便于阅读而缩进和修剪):

var profile={
  "lastUpdatedBy": "Dropbox",
  "updatedAt": 1362617665,
  "profileName": "default",
  "salt": "W0wV8jBiFnRWmqWDl3vaPA==",
  "passwordHint": "hint",
  "masterKey": "b3BkYXRhMDEAAQAAAAAAAGnpNQQJuFTg ..."
  "iterations": 20000,
  "uuid": "A2C1050B56C89557AC2A0FA230F90174",
  "overviewKey": "b3BkYXRhMDFAAAAAAAAAAAbP+65OIhYy ...",
  "createdAt": 1362617665
};

Keychain Instance Methods

Events

事件是使用 NodeJS EventEmitter 实现的。 该 API 可在 NodeJS.org 网站

使用 EventEmitter:

keychain = new Keychain();
keychain.event.on('event', function(args) {
    console.log('Event fired!', args);
});
keychain.event.emit('event', 'random data');

Event: 'unlock'

function() { }

当钥匙串解锁时。

Event: 'lock:before'

function (autolock) { }

当钥匙链被锁定时。 如果钥匙串被自动锁定 计时器,则 autolock 将为真。 用于在钥匙串之前运行代码 锁定。

Event: 'lock:after'

function (autolock) { }

当钥匙链被锁定时。 如果钥匙串被 计时器,则 autolock 将为真。 用于在钥匙串有后运行代码 被锁定。

Loading data from files

从磁盘上的文件加载钥匙串数据。

load(filepath, callback)

这是主要的加载功能,可能是您唯一需要使用的功能。 filepath 指向一个 .cloudkeychain 文件夹,它将遍历并加载使用其他函数找到的所有文件。

keychain.load( './1password.cloudkeychain', function(err) {
    if ( err ) return console.log( err.message );
    console.log( 'Successfully loaded keychain' );
});

loadProfile(filepath, rawData)

profile.js 文件数据加载到钥匙串中。 如果您已经有 profile.js,则将 rawData 设置为 true

filename = './1password.cloudkeychain/default/profile.js';
keychain.loadProfile( filename );

// Alternative
profileData = readFileContents( filename )
keychain.loadProfile( profileData, true )

loadFolders(filepath)

警告:尚未实施。

folders.js 文件数据加载到钥匙串中。

keychain.loadFolders( './1password.cloudkeychain/default/folders.js' );

loadBands(bands)

bands 是指向每个 band 文件的文件路径数组。

keychain.loadBands([
  './1password.cloudkeychain/default/band_0.js',
  './1password.cloudkeychain/default/band_1.js',
  './1password.cloudkeychain/default/band_2.js'
]);

loadAttachment(attachments)

警告:尚未实现

attachments 是指向每个 band 文件的文件路径数组。

keychain.loadAttachments([
  './1password.cloudkeychain/default/026AA7B7333B4F925F16DE9E21B912B7_5754B83288A34CD39DE64B45C2F05A9D.attachment',
  './1password.cloudkeychain/default/6F8CDF100CC99FD55053B77492D97487_072A1462CBDE4E2488FB2DA16D96B84B.attachment'
]);

Unlocking data

处理钥匙串解锁状态。

unlock(password)

使用 password 解锁钥匙串的主键和概览键。 它会在 60 秒后自动锁定自己,除非调用 rescheduleAutoLock

status = keychain.unlock( 'password' );
console.log( 'Keychain was unlocked successfully: ' + status );

lock()

锁上钥匙链。 这将转储所有解密数据的内容,将状态返回到钥匙串最初被锁定时。

keychain.lock();

rescheduleAutoLock()

这将重新安排自动锁定时间。 仅当用户在应用程序中执行重要操作时才应调用它。

keychain.rescheduleAutoLock()

changePassword(currentPassword, newPassword)

警告:尚未测试

此函数将使用 newPassword 重新生成主密钥和概览密钥。 currentPassword 是必需的,因为它没有存储在内存中以确保安全 原因。

keychain.changePassword( 'fred', 'phil' );

Items

处理项目。

createItem(data)

使用 data 中的信息创建项目的新实例。 它返回项目实例,但不会将其添加到钥匙串中。 使用 addItem() 来做到这一点。

item = keychain.createItem({
  title: 'Github',
  username: 'wendyappleseed',
  password: 'password',
  url: 'github.com',
  notes: ''
});

addItem(item)

将项目添加到钥匙串。 如果 item 不是项目的实例,则使用 new Item(item) 将其变成一个。

keychain.addItem(item);

getItem(uuid)

通过 UUID 获取项目。

item = keychain.getItem('B1198E4C643E73A6226B89BB600371A9');

findItems(query)

按名称或位置在钥匙串中搜索项目。 返回项目数组。

items = keychain.findItems('github');

eachItem(fn)

遍历钥匙串中的所有项目。 使用参数 [item] 调用 fn。

keychain.eachItem(function(item) {
  console.log( item );
});

Exporting Data

将钥匙串数据导出为字符串化的 JSON。 准备写入磁盘。

exportProfile()

导出 profile.js 文件。

profile = keychain.exportProfile();
writeFile('profile.js', profile);

exportBands()

导出乐队文件(其中包含项目数据)。 返回一个对象。

bands = keychain.exportBands()

console.log( bands );

{
  "band_0.js": "ld({\n  \"B1198E4C643E73A6226B89BB600371A9\": {\n    \"category\": \"001\" ...",
  filename: filedata
}

Item Instance Methods

load(data)

这用于将 band 文件中的原始 JSON 数据加载到项目中。 hmackod 等字段是从 base64 转换而来的。

item.load({
    category: '106',
    created: 1361850113,
    d: 'b3BkYXRhMDHlAgAAAAAAANQpT0oUzF1E ...',
    hmac: '/Qzi7Gy37hIV18NgXffDMmt3iPZKVxIFlvvULxf5iCQ=',
    k: '3OoNrhpqKeBkeVAHTgwXPjlEL++QJAhx ...',
    o: 'b3BkYXRhMDElAAAAAAAAAEfvS1hvP9Ue …',
    tx: 1361857114,
    updated: 1361857114,
    uuid: 'F11FC7E27E3645D09D2670F04EF5F252'
});

lock(type)

通过删除项目密钥、概览数据和详细信息等安全信息来锁定项目。

console.log( item.overview ); // {...} Overview data
item.lock('overview');
console.log( item.overview ); // undefined

unlock(type)

通过解密项目密钥、概览数据和详细信息等安全信息来解锁项目。

details = item.unlock('details')

encrypt(type)

加密项目详细信息。

item.unlock('details');
item.details.data = true;
item.encrypt('details');
item.lock('details');

toJSON()

将项目导出到可以保存在带文件中的 JSON 对象中。

json = item.toJSON();

match(query)

检查项目是否与查询匹配。 用于搜索钥匙串。 它检查项目的标题和 URL,并且不区分大小写。

item.overview.title == 'Facebook';
item.match('facebook'); // true
item.match('book');     // true
item.match('skype');    // false

Compiling

要将 coffeescript 编译成 javascript,请使用 cake

cake build

Tests

测试是使用 Mocha 用 Ja​​vaScript 编写的。 运行测试

sudo npm install -g mocha
mocha tests

或者如果您不想全局安装 mocha:

npm install .
cake tests

另外请记住在测试之前重新编译 coffeescript!

License

这项工作已获得 ISC 许可。

Cloud Keychain for Node.js (v0.2.1)

This is a small library to make it easy to work with 1Password's .cloudKeychain files.

This implementation is based on the official Agile Bits documentation and also the python library OnePasswordPy.

IMPORTANT NOTE: I am not in any way affiliated with AgileBits, the makers of 1Password. Their software is awesome and you should probably go buy it.

Currently supported:

  • Unlock keychain using Master Password
  • Load items from band_*.js files
  • Unlock item overview, keys and details
  • Create keychains and items

Todo:

  • Find out how to calcuate the HMAC of items correctly
  • Actually do something with item data (instead of just handing back the raw JSON)
  • Get syncing working.
  • Add memoize pattern to opdata class to speed up item locking when no data has changed.

Installation

npm install 1password

How to Use

Step 1: Open the keychain

Keychain = require( '1password' );
keychain = new Keychain();
keychain.load( './1password.cloudkeychain', function( err ) {
    console.log( 'Keychain has loaded' ); 
});

Step 2: Unlocking the keychain

keychain.unlock( 'password' );

if ( keychain.unlocked ) {
    console.log( 'Successfully unlocked keychain' );
} else {
    console.log( 'Error: Could not unlock keychain' );
}

Step 3: Get items

keychain.eachItem( function( item ) {
  console.log( item );
});

Step 4: Decrypt item details

item = keychain.findItems( 'Facebook' )[0];
item.unlockDetails();
console.log( item.details );

Main Keychain Methods

Keychain.create(password, settings)

Returns an empty keychain encrypted using the password specified.

keychain = Keychain.create( 'password', {
    passwordHint: 'hint'
});
profile = keychain.exportProfile();
console.log( profile );

The settings parameter is an object and can overwrite any of the default values. However extra settings cannot be added. The default settings are:

settings = {
  uuid: Crypto.generateUuid(),
  salt: Crypto.randomBytes(16),
  createdAt: currentTime,
  updatedAt: currentTime,
  iterations: 10000,
  profileName: 'default',
  passwordHint: '',
  lastUpdatedBy: 'Dropbox'
};

This logs the following (indented and trimmed for readibility):

var profile={
  "lastUpdatedBy": "Dropbox",
  "updatedAt": 1362617665,
  "profileName": "default",
  "salt": "W0wV8jBiFnRWmqWDl3vaPA==",
  "passwordHint": "hint",
  "masterKey": "b3BkYXRhMDEAAQAAAAAAAGnpNQQJuFTg ..."
  "iterations": 20000,
  "uuid": "A2C1050B56C89557AC2A0FA230F90174",
  "overviewKey": "b3BkYXRhMDFAAAAAAAAAAAbP+65OIhYy ...",
  "createdAt": 1362617665
};

Keychain Instance Methods

Events

Events are implemented using the NodeJS EventEmitter. The API is available on the NodeJS.org website.

To use the EventEmitter:

keychain = new Keychain();
keychain.event.on('event', function(args) {
    console.log('Event fired!', args);
});
keychain.event.emit('event', 'random data');

Event: 'unlock'

function() { }

When the keychain is unlocked.

Event: 'lock:before'

function (autolock) { }

When the keychain is locked. If the keychain was locked automatically by a timer, then autolock will be true. Used to run code before the keychain is locked.

Event: 'lock:after'

function (autolock) { }

When the keychain is locked. If the keychain was locked automatically by the timer, then autolock will be true. Used to run code after the keychain has been locked.

Loading data from files

Load keychain data from a file on disk.

load(filepath, callback)

This is the main loading function and probably the only one you'll only ever need to use. filepath points to a .cloudkeychain folder and it will go through and load all files it finds using the other functions.

keychain.load( './1password.cloudkeychain', function(err) {
    if ( err ) return console.log( err.message );
    console.log( 'Successfully loaded keychain' );
});

loadProfile(filepath, rawData)

Loads the profile.js file data into the keychain. If you already have profile.js then set rawData to true.

filename = './1password.cloudkeychain/default/profile.js';
keychain.loadProfile( filename );

// Alternative
profileData = readFileContents( filename )
keychain.loadProfile( profileData, true )

loadFolders(filepath)

Warning: Not yet implemented.

Load the folders.js file data into the keychain.

keychain.loadFolders( './1password.cloudkeychain/default/folders.js' );

loadBands(bands)

bands is an array of filepaths pointing to each band file.

keychain.loadBands([
  './1password.cloudkeychain/default/band_0.js',
  './1password.cloudkeychain/default/band_1.js',
  './1password.cloudkeychain/default/band_2.js'
]);

loadAttachment(attachments)

Warning: Not yet implemented

attachments is an array of filepaths pointing to each band file.

keychain.loadAttachments([
  './1password.cloudkeychain/default/026AA7B7333B4F925F16DE9E21B912B7_5754B83288A34CD39DE64B45C2F05A9D.attachment',
  './1password.cloudkeychain/default/6F8CDF100CC99FD55053B77492D97487_072A1462CBDE4E2488FB2DA16D96B84B.attachment'
]);

Unlocking data

Handle the keychain unlocked status.

unlock(password)

Unlock the keychain's master and overview keys using password. It will automatically lock itself after 60 seconds, unless rescheduleAutoLock is called.

status = keychain.unlock( 'password' );
console.log( 'Keychain was unlocked successfully: ' + status );

lock()

Lock the keychain. This will dump the contents of all decrypted data, returning the state back to when the keychain was originally locked.

keychain.lock();

rescheduleAutoLock()

This will reschedule the autolock time. It should only be called when the user does something importantt in the app.

keychain.rescheduleAutoLock()

changePassword(currentPassword, newPassword)

Warning: Not yet tested

This function will regenerate the master and overview keys using newPassword. The currentPassword is required, as it is not stored in memory for security reasons.

keychain.changePassword( 'fred', 'phil' );

Items

Working with items.

createItem(data)

Creates a new instance of an item using the information in data. It returns the item instance, but it does not add it to the keychain. Use addItem() to do that.

item = keychain.createItem({
  title: 'Github',
  username: 'wendyappleseed',
  password: 'password',
  url: 'github.com',
  notes: ''
});

addItem(item)

Adds an item to the keychain. If item is not an instance of an item, it is turned into one using new Item(item).

keychain.addItem(item);

getItem(uuid)

Get an item by its UUID.

item = keychain.getItem('B1198E4C643E73A6226B89BB600371A9');

findItems(query)

Search the keychain for an item by its name or location. Returns an array of items.

items = keychain.findItems('github');

eachItem(fn)

Loop through all the items in the keychain. Calls fn with the arguments [item].

keychain.eachItem(function(item) {
  console.log( item );
});

Exporting Data

Export keychain data into stringified JSON. Ready for writing to disk.

exportProfile()

Export the profile.js file.

profile = keychain.exportProfile();
writeFile('profile.js', profile);

exportBands()

Export the band files (which holds the item data). Returns an object.

bands = keychain.exportBands()

console.log( bands );

{
  "band_0.js": "ld({\n  \"B1198E4C643E73A6226B89BB600371A9\": {\n    \"category\": \"001\" ...",
  filename: filedata
}

Item Instance Methods

load(data)

This is used to load the raw JSON data in a band file into an item. Fields such as hmac, k, o and d are converted from base64.

item.load({
    category: '106',
    created: 1361850113,
    d: 'b3BkYXRhMDHlAgAAAAAAANQpT0oUzF1E ...',
    hmac: '/Qzi7Gy37hIV18NgXffDMmt3iPZKVxIFlvvULxf5iCQ=',
    k: '3OoNrhpqKeBkeVAHTgwXPjlEL++QJAhx ...',
    o: 'b3BkYXRhMDElAAAAAAAAAEfvS1hvP9Ue …',
    tx: 1361857114,
    updated: 1361857114,
    uuid: 'F11FC7E27E3645D09D2670F04EF5F252'
});

lock(type)

Lock the item by deleting secure information such as the item keys, overview data and details.

console.log( item.overview ); // {...} Overview data
item.lock('overview');
console.log( item.overview ); // undefined

unlock(type)

Unlock the item by decrypting secure information such as the item keys, overview data and details.

details = item.unlock('details')

encrypt(type)

Encrypt item details.

item.unlock('details');
item.details.data = true;
item.encrypt('details');
item.lock('details');

toJSON()

Export an item into a JSON object that can be saved in a band file.

json = item.toJSON();

match(query)

Check if an item matches a query. Useful for searching through a keychain. It checks the title and URL of the item and is case insensitive.

item.overview.title == 'Facebook';
item.match('facebook'); // true
item.match('book');     // true
item.match('skype');    // false

Compiling

To compile the coffeescript into javascript use cake:

cake build

Tests

Tests are written in JavaScript using Mocha. To run the tests

sudo npm install -g mocha
mocha tests

Or if you don't want to install mocha globally:

npm install .
cake tests

Also remember to recompile the coffeescript before testing!

License

This work is licensed under the ISC license.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文