JavaScript SDK
Keeperシークレットマネージャー用Javascript SDKの詳細
ダウンロードとインストール
NPMによるインストール
npm install @keeper-security/secrets-manager-coreソースコード
JavaScriptのソースコードは、GitHubリポジトリで入手できます。
SDKの使用
ストレージの初期化
シークレットを取得するには、まずマシンのローカルストレージを初期化する必要があります。
initializeStorage(storage:KeyValueStorage, clientKey:String? = null, hostName:String? = null)storage
KeyValueStorage
はい
保存場所
clientKey
string
オプション
null
Keeperシークレットマネージャーに接続するためのトークン
hostName
string
オプション
null
シークレットを取得するサーバーの場所。 何も指定しない場合は、keepersecurity.com (米国) が使用されます
使用例
const { getSecrets, initializeStorage, localConfigStorage } = require('@keeper-security/secrets-manager-core')
const getKeeperRecords = async () => {
// oneTimeTokenはストレージの初期化に一度だけ使用
// 初回実行以降の呼び出しでは、ksm-config.txtを使用
const oneTimeToken = "<One Time Access Token>";
const storage = localConfigStorage("ksm-config.json")
await initializeStorage(storage, oneTimeToken)
// トークンのみを使用して(後で使用するために)設定を生成するには
// トークンをバインドするアクセス操作が少なくとも1回必要です
//await getSecrets({storage: storage})
const {records} = await getSecrets({storage: storage})
console.log(records)
const firstRecord = records[0]
const firstRecordPassword = firstRecord.data.fields.find(x => x.type === 'password')
console.log(firstRecordPassword.value[0])
}
getKeeperRecords().finally()シークレットの取得
getSecrets(options:SecretsManagerOptions, recordsFilter:List<String> = emptyList()):KeeperSecretsstorage
KeyValueStorage
はい
保存場所
recordsFilter
string[]
オプション
空のリスト
取得するUIDレコード
レスポンス
型: KeeperSecrets
すべてのKeeperのレコード、または指定したフィルタ条件に一致するレコードを含むオブジェクト
使用例
すべてのシークレットを取得
const storage = inMemoryStorage() // see initialization example
val secrets = getSecrets(storage)タイトルでシークレットを取得
// 一致するレコードをすべて取得
getSecretsByTitle = async (options:SecretManagerOptions, recordTitle: string):Promise<KeeperRecord[]>
// 最初に一致したレコードだけを取得
getSecretByTitle = async (options:SecretManagerOptions, recordTitle: string):Promise<KeeperRecord>options
SecretsManagerOptions
はい
事前に設定されたオプション
recordTitle
string
はい
検索するレコードタイトル
使用例
const {
getSecretByTitle,
localConfigStorage,
} = require('@keeper-security/secrets-manager-core')
const getKeeperRecord = async () => {
const options = { storage: localConfigStorage("ksm-config.json")
const {myCredential} = await getSecretByTitle(options, "My Credential")
}
getKeeperRecord().finally()シークレットから値を取得
パスワードを取得
secret.data.fields.find(x => x.type === 'password')const { getSecrets, initializeStorage, localConfigStorage } = require('@keeper-security/secrets-manager-core')
const getKeeperRecords = async () => {
const storage = localConfigStorage("ksm-config.json")
// レコードを取得
const {records} = await getSecrets({storage: storage})
// 最初のレコードからパスワードを取得
const firstRecord = records[0]
const firstRecordPassword = firstRecord.data.fields.find(x => x.type === 'password')
}フィールドタイプはKeeperレコードタイプに基づきます。利用可能なフィールドの詳細な一覧については、コマンダーで record-type-info コマンドをご参照ください。
Keeper表記法を使用して他のフィールドを取得
getValue(secrets:KeeperSecrets, query: string): anyconst {
getSecrets,
localConfigStorage,
getValue
} = require('@keeper-security/secrets-manager-core')
const getKeeperRecords = async () => {
const options = { storage: localConfigStorage("ksm-config.json") }
// シークレットを取得
const secrets = await getSecrets(options)
// ドット記法でログインを取得
const loginValue = getValue(secrets, 'RECORD_UID/field/login')
}secrets
KeeperSecrets
はい
照会するシークレット
query
string
はい
Keeper表記法を使用したクエリ
この表記を使用したクエリで指定するレコードUIDは、
secretsパラメーターで渡されたシークレットのいずれかである必要があります。そうでない場合、クエリでは何も取得されません。
戻り値
型: any
ドット記法を使用したクエリで指定された位置のフィールドに値が存在する場合はその値 (存在しない場合は不定)
TOTPコードを取得
getTotpCode(url: string): stringconst {
getSecrets,
localConfigStorage,
getTotpCode,
getValue} = require('@keeper-security/secrets-manager-core')
const getKeeperRecords = async () => {
const options = { storage: localConfigStorage("ksm-config.json") }
// シークレットを取得
const secrets = await getSecrets(options)
// ドット記法でログインを取得
const totpUri = getValue(secrets,'RECORD_UID/field/oneTimeCode')
// TOTPコードを取得
const totp = await getTotpCode(totpUri)
}url
string
はい
TOTP Url
この表記を使用したクエリで指定するレコードUIDは、
secretsパラメーターで渡されたシークレットのいずれかである必要があります。そうでない場合、クエリでは何も取得されません。
戻り値
型: any
ドット記法を使用したクエリで指定された位置のフィールドに値が存在する場合はその値 (存在しない場合は不定)
シークレットを更新
レコードを更新するコマンドは、成功してもローカルのレコード情報 (特に「リビジョン番号」) が自動では更新されません。そのため、同じレコードに続けて更新を行うと、「リビジョンが合っていない」というエラーで失敗してしまいます。そのため、レコードを更新した後は、必ずそのレコードを最新の状態に再読み込みしてください。
updateSecret(options, record)const {
getSecrets,
localConfigStorage,
updateSecret} = require('@keeper-security/secrets-manager-core')
const storage = localConfigStorage("ksm-config.json")
// レコードを取得
const {records} = await getSecrets({storage: storage})
// 最初のレコードを取得
const recordToUpdate = records[0]
// 新しいレコードタイトルを設定
recordToUpdate.data.title = 'New Title'
// レコードの変更を保存
await updateSecret(options, recordToUpdate)const {
getSecrets,
localConfigStorage,
updateSecret,
completeTransaction,
UpdateTransactionType,
SecretManagerOptions
} = require('@keeper-security/secrets-manager-core')
// レコードを取得
const options = { storage: localConfigStorage("ksm-config.json") }
const {records} = await getSecrets(options)
// 最初のレコードのパスワードをローテーション
const secret = records[0]
const password = secret.data.fields.find(x => x.type === "password")
password.value[0] = "MyNewPassword"
// ボールト内のレコードを更新するためにトランザクションを開始
await updateSecret(options, secret, UpdateTransactionType.Rotation)
// リモートホスト上のパスワードをローテーション
const success = rotateRemoteSshPassword("MyNewPassword");
// トランザクションを完了(コミットまたはロールバック)
const rollback = !success
await completeTransaction(options, secret.recordUid, rollback)
options
SecretManagerOptions
はい
record
KeeperRecord
はい
戻り値
型: Promise<void>
ランダムなパスワードを生成
generatePassword(length, lowercase, uppercase, digits, specialCharacters)const {
getSecrets,
localConfigStorage,
updateSecret,
generatePassword } = require('@keeper-security/secrets-manager-core')
// ランダムなパスワードを生成
let newRandomPwd = await generatePassword()
const storage = localConfigStorage("ksm-config.json")
const {records} = await getSecrets({storage: storage})
// 最初のレコードを取得
const recordToUpdate = records[0]
// タイプが「password」のフィールドを検索
const recordToUpdatePasswordField = recordToUpdate.data.fields.find(x => x.type === 'password')
// passwordフィールドに新しい値を設定
recordToUpdatePasswordField.value[0] = newRandomPwd
await updateSecret({storage: storage}, recordToUpdate)length
int
オプション
64
lowercase
int
オプション
0
uppercase
int
オプション
0
digits
int
オプション
0
specialCharacters
int
オプション
0
各パラメーターは、それぞれの文字タイプを最低何文字含めるかを指定します。たとえば、uppercase は「大文字を最低何文字含めるか」を示します。
戻り値
型: String
ファイルのダウンロード
downloadFile(file:KeeperFile):ByteArrayfile
KeeperFile
はい
ダウンロードするファイル
レスポンス
型: Promise<Uint8Array>
ダウンロード用のファイルのバイト列
サムネイルのダウンロード
downloadThumbnail(file:KeeperFile):ByteArrayfile
KeeperFile
はい
ダウンロードするサムネイル付きファイル
レスポンス
型: Promise<Uint8Array>
ダウンロード用サムネイルのバイト列
ファイルのアップロード
ファイルのアップロード:
uploadFile = async (options:SecretManagerOptions, ownerRecord:KeeperRecord, file:KeeperFileUpload):Promise<string>options
SecretsManagerOptions
はい
ストレージとクエリの設定
ownerRecord
KeeperRecord
はい
アップロードされたファイルを添付するレコード
file
KeeperFileUpload
はい
アップロードするファイル
Keeperファイルアップロードオブジェクトを作成:
type KeeperFileUpload = {
name: string
title: string
type?: string
data:Uint8Array
}name
string
はい
アップロード後にKeeperに格納されるファイルの名前
title
string
はい
アップロード後にKeeperに格納されるファイルのタイトル
type
string
オプション
ファイルのデータのMIMEタイプ。何も指定しない場合は、「application/octet-stream」が使用されます
data
Uint8Array
はい
バイト型のファイルデータ
使用例
// ファイルを添付するレコードを取得
const {records} = await getSecrets({storage: storage}, ['XXX'])
const ownerRecord = records[0]
// アップロードするファイルデータを取得
const fileData = fs.readFileSync('./assets/my-file.json')
// 選択したレコードにファイルをアップロード
await uploadFile(options, ownerRecord, {
name: 'my-file.json',
title:'Sample File',
type: 'application/json',
data: fileData
})シークレットの作成
要件
共有フォルダのUID
共有フォルダには、シークレットマネージャーアプリケーションからアクセスできること
ユーザーとシークレットマネージャーアプリケーションには編集権限が付与されていること
共有フォルダには、少なくとも1つのレコードが存在すること
作成されたレコードとレコードのフィールドは正しい形式で設定されていること
各レコードタイプのフィールド形式については、こちらのページをご参照ください
TOTPフィールドには、KSM SDK以外で生成されたURLのみを指定できます
レコードを作成した後、
uploadFileを使用して添付ファイルをアップロードできます
createSecret(options, folderUid, record)options
SecretManagerOptions
はい
folderUid
string
はい
record
JSON Object
はい
createSecret2(options, createOptions, record)options
SecretManagerOptions
はい
createOptions
CreateOptions
はい
record
JSON Object
はい
この例では、ログイン値と生成されたパスワードを含むログイン情報タイプのレコードを作成します。
let newRec = {
"title":"Sample KSM Record:JavaScript",
"type": "login",
"fields": [
{ "type": "login", "value": [ "[email protected]" ] },
{ "type": "password", "value": [ await generatePassword() ] }
],
"notes":"This is a JavaScript record creation example"
}
let recordUid = await createSecret(options, folderUid, newRec)この例では、カスタムのレコードタイプのレコードを作成します。
let newRec = {
"title":"Sample Custom Type KSM Record:JavaScript",
"type":"Custom Login",
"fields": [
{
"type": "host",
"label":"My Custom Host lbl",
"value": [ {"hostName":"127.0.0.1", "port":"8080"} ],
"required": true,
"privacyScreen": false
},
{
"type": "login",
"label":"My Custom Login lbl",
"value": [ "[email protected]" ],
"required": true,
"privacyScreen": false
},
{
"type": "password",
"label":"My Custom Password lbl",
"value": [ await generatePassword() ],
"required": true,
"privacyScreen": false
},
{
"type": "url",
"label":"My Login Page",
"value": [ "http://localhost:8080/login" ],
"required": true,
"privacyScreen": false
},
{
"type": "securityQuestion",
"label":"My Question 1",
"value": [ {
"question":"What is one plus one (write just a number)",
"answer":"2"
} ],
"required": true,
"privacyScreen": false
},
{
"type": "phone",
"value": [{
"region":"US",
"number":"510-444-3333",
"ext":"2345",
"type":"Mobile"
}],
"label":"My Phone Number"
},
{
"type": "date",
"value": [ 1641934793000 ],
"label":"My Date Lbl",
"required": true,
"privacyScreen": false
},
{
"type": "name",
"value": [{
"first":"John",
"middle":"Patrick",
"last":"Smith"
}],
"label":"My Custom Name lbl",
"required": true,
"privacyScreen": false
},
{
"type": "oneTimeCode",
"label":"My TOTP",
"value": ["otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example"],
"required": true,
"privacyScreen": false
}
],
"custom": [
{
"type": "phone",
"value": [{
"region":"US",
"number": "(510) 123-3456"
}],
"label":"My Custom Phone Lbl 1"
},
{
"type": "phone",
"value": [ {
"region":"US",
"number":"510-111-3333",
"ext":"45674",
"type":"Mobile" } ],
"label":"My Custom Phone Lbl 2"
}
],
"notes": "\tThis custom type record was created\n\tvia KSM Katacoda JavaScript Example"
}
let recordUid = await createSecret(options, "[FOLDER UID]", newRec)シークレットの削除
JavaScript KSM SDKでKeeperボルトのレコードを削除できます。
deleteSecret(smOptions, recordUids);smOptions
SecretManagerOptions
はい
recordUids
string[]
はい
// シークレットマネージャーを設定
const smOptions = { storage: localConfigStorage("ksm-config.json")
// レコードUIDで特定のシークレットを削除
await deleteSecret(smOptions, ["EG6KdJaaLG7esRZbMnfbFA"]);キャッシュ
ネットワークへのアクセスが失われた際にシークレットへのアクセスも失うという事態を避けるため、JavaScript SDKでは、シークレットを暗号化されたファイルとしてローカルマシンにキャッシュすることができます。
SecretManagerOptions に queryFunction: cachingPostFunction を追加
使用例:
const options:SecretManagerOptions = {
storage: kvs,
queryFunction: cachingPostFunction // `cachingPostFunction` をインポートする
}フォルダ
フォルダは完全なCRUD (作成、読み取り、更新、削除操作) に対応しています。
フォルダの読み取り
フォルダの完全な階層構造をダウンロードします。
getFolders = async (options:SecretManagerOptions):Promise<KeeperFolder[]>レスポンス
型: KeeperFolder[]
使用例
const storage = localConfigStorage("ksm-config.json")
const folders = await getFolders({storage: storage})フォルダの作成
作成には CreateOptions とフォルダ名の指定が必要です。CreateOptions に含まれる folder UID パラメータは必須で、これは共有フォルダのUIDを指定します。sub-folder UID は任意で、省略された場合は、指定された共有フォルダの直下に通常のフォルダが新規作成されます。なお、sub-folder UID は必ずしも親の共有フォルダの直下である必要はなく、何階層も深い位置を指定することも可能です。
createFolder = async (options:SecretManagerOptions, createOptions:CreateOptions, folderName: string):Promise<string>options
SecretsManagerOptions
はい
事前に設定されたオプション
createOptions
CreateOptions
はい
親およびサブフォルダのUID
folderName
string
はい
フォルダ名
type CreateOptions = {
folderUid: string
subFolderUid?: string
}使用例
const storage = localConfigStorage("ksm-config.json")
const folderUid = await createFolder({storage: storage}, {folderUid: "[SHARED_FOLDER_UID]"}, "new_folder")フォルダの更新
フォルダのメタデータ (現在はフォルダ名のみ) を更新します。
updateFolder = async (options:SecretManagerOptions, folderUid: string, folderName: string):Promise<void>options
SecretsManagerOptions
はい
事前に設定されたオプション
folderUid
string
はい
フォルダのUID
folderName
string
はい
新しいフォルダ名
使用例
const storage = localConfigStorage("ksm-config.json")
await updateFolder({storage: storage}, "[FOLDER_UID]", "new_folder_name")フォルダの削除
フォルダのリストを削除します。空でないフォルダを削除するには、forceDeletionフラグを使用します。
deleteFolder = async (options:SecretManagerOptions, folderUids: string[], forceDeletion?: boolean):Promise<SecretsManagerDeleteResponse>options
SecretsManagerOptions
はい
事前に設定されたオプション
folderUids
string[]
はい
フォルダUIDリスト
forceDeletion
bool
いいえ
false
空でないフォルダを強制的に削除
使用例
const storage = localConfigStorage("ksm-config.json")
await deleteFolder({storage: storage}, ["[FOLDER_UID1]", "[FOLDER_UID2]"], true)最終更新

