server location to get secrets. If nothing is passed, will use keepersecurity.com (US)
Example Usage
const { getSecrets,initializeStorage,localConfigStorage } =require('@keeper-security/secrets-manager-core')constgetKeeperRecords=async () => {// oneTimeToken is used only once to initialize the storage// after the first run, subsequent calls will use ksm-config.txtconstoneTimeToken="<One Time Access Token>";conststorage=localConfigStorage("ksm-config.json")awaitinitializeStorage(storage, oneTimeToken)// Using token only to generate a config (for later usage)// requires at least one access operation to bind the token//await getSecrets({storage: storage})const {records} =awaitgetSecrets({storage: storage})console.log(records)constfirstRecord= records[0]constfirstRecordPassword=firstRecord.data.fields.find(x =>x.type ==='password')console.log(firstRecordPassword.value[0])}getKeeperRecords().finally()
Object containing all Keeper records, or records that match the given filter criteria
Example Usage
Retrieve all Secrets
conststorage=inMemoryStorage() // see initialization exampleval secrets =getSecrets(storage)
Retrieve Secrets by Title
// get all matching recordsgetSecretsByTitle=async (options:SecretManagerOptions, recordTitle:string):Promise<KeeperRecord[]>// get only the first matching recordgetSecretByTitle = async (options:SecretManagerOptions, recordTitle:string):Promise<KeeperRecord>
* The record UID in the notation query must be for a secret passed in the secrets parameter or nothing will be found by the query
Returns
Type: any
The value of the field at the location specified by the dot notation query if any, otherwise undefined.
Update a Secret
Record update commands don't update local record data on success (esp. updated record revision) so any consecutive updates to an already updated record will fail due to revision mismatch. Make sure to reload all updated records after each update batch.
updateSecret(options, record)
const { getSecrets,localConfigStorage,updateSecret} =require('@keeper-security/secrets-manager-core')conststorage=localConfigStorage("ksm-config.json")// get recordsconst {records} =awaitgetSecrets({storage: storage})// get the first recordconstrecordToUpdate= records[0]// set new record titlerecordToUpdate.data.title ='New Title'// save record changesawaitupdateSecret(options, recordToUpdate)
const { getSecrets,localConfigStorage,updateSecret,completeTransaction,UpdateTransactionType,SecretManagerOptions} =require('@keeper-security/secrets-manager-core')// get recordsconstoptions= { storage:localConfigStorage("ksm-config.json") }const {records} =awaitgetSecrets(options)// rotate password on the first recordconstsecret= records[0]constpassword=secret.data.fields.find(x =>x.type ==="password")password.value[0] ="MyNewPassword"//start a transaction to update record in vaultawaitupdateSecret(options, secret,UpdateTransactionType.Rotation)// rotate password on remote hostconstsuccess=rotateRemoteSshPassword("MyNewPassword");// complete the transaction - commit or rollbackconstrollback=!successawaitcompleteTransaction(options,secret.recordUid, rollback)
const { getSecrets,localConfigStorage,updateSecret,generatePassword } =require('@keeper-security/secrets-manager-core')// generate a random passwordlet newRandomPwd =awaitgeneratePassword()conststorage=localConfigStorage("ksm-config.json")const {records} =awaitgetSecrets({storage: storage})// get the first recordconstrecordToUpdate= records[0]// Find the field with the type "password"constrecordToUpdatePasswordField=recordToUpdate.data.fields.find(x =>x.type ==='password')// set new value to the password fieldrecordToUpdatePasswordField.value[0] = newRandomPwdawaitupdateSecret({storage: storage}, recordToUpdate)
Parameter
Type
Required
Default
length
int
Optional
64
lowercase
int
Optional
0
uppercase
int
Optional
0
digits
int
Optional
0
specialCharacters
int
Optional
0
Each parameter indicates the min number of a type of character to include. For example, 'uppercase' indicates the minimum number of uppercase letters to include.
What the name of the file will be in Keeper once uploaded
title
string
Yes
What the title of the file will be in Keeper once uploaded
type
string
Optional
The mime type of data in the file. 'application/octet-stream' will be used if nothing is given
data
Uint8Array
Yes
File data as bytes
Example Usage
// get record to attach file toconst {records} =awaitgetSecrets({storage: storage}, ['XXX'])constownerRecord= records[0]// get file data to uploadconstfileData=fs.readFileSync('./assets/my-file.json')// upload file to selected recordawaituploadFile(options, ownerRecord, { name:'my-file.json', title:'Sample File', type:'application/json', data: fileData})
Create a Secret
Prerequisites:
Shared folder UID
Shared folder must be accessible by the Secrets Manager Application
You and the Secrets Manager application must have edit permission
There must be at least one record in the shared folder
Created records and record fields must be formatted correctly
See the documentation for expected field formats for each record type
TOTP fields accept only URL generated outside of the KSM SDK
After record creation, you can upload file attachments using uploadFile
createSecret(options, folderUid, record)
Parameter
Type
Required
Default
options
SecretManagerOptions
Yes
folderUid
string
Yes
record
JSON Object
Yes
createSecret2(options, createOptions, record)
Parameter
Type
Required
Default
options
SecretManagerOptions
Yes
createOptions
CreateOptions
Yes
record
JSON Object
Yes
This example creates a login type record with a login value and a generated password.
Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager has access to.
let newRec = {"title":"Sample KSM Record: JavaScript","type":"login","fields": [ { "type":"login","value": [ "username@email.com" ] }, { "type":"password","value": [ awaitgeneratePassword() ] } ],"notes":"This is a JavaScript record creation example"}let recordUid =awaitcreateSecret(options, folderUid, newRec)
This example creates a record with a custom record type.
Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager has access to.
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": [ "login@email.com" ],"required":true,"privacyScreen":false }, {"type":"password","label":"My Custom Password lbl","value": [ awaitgeneratePassword() ],"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:alice@google.com?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 =awaitcreateSecret(options,"[FOLDER UID]", newRec)
Delete a Secret
The JavaScript KSM SDK can delete records in the Keeper Vault.
deleteSecret(smOptions, recordUids);
Parameter
Type
Required
smOptions
SecretManagerOptions
Yes
recordUids
string[]
Yes
// setup secrets managerconstsmOptions= { storage:localConfigStorage("ksm-config.json") // delete a specific secret by record UIDawaitdeleteSecret(smOptions, ["EG6KdJaaLG7esRZbMnfbFA"]);
Caching
To protect against losing access to your secrets when network access is lost, the JavaScript SDK allows caching of secrets to the local machine in an encrypted file.
Add queryFunction: cachingPostFunction to SecretManagerOptions
Requires CreateOptions and folder name to be provided. The folder UID parameter in CreateOptions is required - UID of a shared folder, while sub-folder UID is optional and if missing new regular folder is created directly under the parent (shared folder). There's no requirement for the sub-folder to be a direct descendant of the parent shared folder - it could be many levels deep.
Removes a list of folders. Use forceDeletion flag to remove non-empty folders.
When using forceDeletion avoid sending parent with its children folder UIDs. Depending on the delete order you may get an error - ex. if parent force-deleted child first. There's no guarantee that list will always be processed in FIFO order.
Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.