API Docs

Store small secrets, such as passwords, API tokens and TOTP seeds, in the macOS keychain, so they don't have to live in your config files.

Each secret is identified by a service and an account, both strings of your choosing. A good convention is to use a host name or a Spoon's name as the service, and a user name as the account.

Secrets are kept in Hammerspoon 2's own part of the keychain (its keychain access group). Other apps can't read, list or even see them, and Hammerspoon 2 can't see any other app's items, such as the passwords saved in the Passwords app. Bear in mind that any code running in Hammerspoon 2, including every Spoon you load, can read every secret stored here, unless it's stored with requireUserPresence.

Secrets can be read while the screen is locked, once you've logged in, so timers and watchers can use them. Reading a secret is asynchronous, because macOS may need to ask you to authenticate first.

Errors are thrown (or rejected, for get()) as Errors with a code property:

Code Meaning
EINVALIDARG An argument or option is missing or malformed
ENOENTITLEMENT This copy of Hammerspoon 2 can't use the keychain, see isAvailable
ECANCELED You cancelled the authentication prompt
EAUTH Authentication failed
EINTERACTION The keychain needed to ask you something, but couldn't
EUNAVAILABLE The keychain isn't available, e.g. before you've logged in
ENOENT A file to import can't be read
EEXIST A certificate or private key to import is already stored under another name
EKEYCHAIN Any other keychain error. The message includes its OSStatus, which is also in the status property

Quick start

Store a secret once, from the Console:

hs.keychain.set("api.example.com", "me", "my-api-token")

Then use it in your config:

hs.keychain.get("api.example.com", "me").then(token => {
    return fetch("https://api.example.com/things", {
        headers: { Authorization: `Bearer ${token}` }
    })
}).then(response => response.json())
  .then(things => console.log(`${things.length} things`))
  .catch(err => console.error(err.message))

HTTP basic authentication

const user = "me"
hs.keychain.get("intranet.example.com", user).then(password => {
    return fetch("https://intranet.example.com/status", {
        headers: { Authorization: "Basic " + hs.hashing.base64Encode(`${user}:${password}`) }
    })
}).then(response => console.log(`Status: ${response.status}`))
  .catch(err => console.error(err.message))

Certificates

Certificates, and certificates with their private keys (identities), can be stored under a name of your choosing, and then used by name for TLS, so neither the certificate files nor their passphrases have to stay on disk or in your config:

  • hs.httpserver's setTLSFromKeychain(name) and hs.socket's enableServerTLSFromKeychain(name) serve TLS with an identity
  • hs.mqtt's caCertificate: "keychain:<name>" option trusts certificates, and its clientCertificate: "keychain:<name>" option identifies the client with an identity

Those look for a certificate stored here first, then for one in your login keychain.

// Once, from the Console:
hs.keychain.importIdentity("my server", "~/Downloads/server.p12", "the passphrase")

// Then in your config:
const server = hs.httpserver.create().setPort(8443).setTLSFromKeychain("my server")

Properties

hs.keychain.isAvailable

boolean

Whether this copy of Hammerspoon 2 can use the keychain. Copies built without code signing (such as development builds made with signing turned off) can't, and every other function then throws an ENOENTITLEMENT error.

Methods

hs.keychain.set(service, account, secret, options) -> None

Store a secret, replacing any secret already stored for the same service and account.

hs.keychain.set(service, account, secret, options) -> None
Name Type Description
service string What the secret is for, such as a host name or a Spoon's name. Can't be empty.
account string Whose secret it is, such as a user name. Can't be empty.
secret string The secret itself
options optional object | null How to store the secret
label optional string A name for the secret, shown by items()
comment optional string A note about the secret, shown by items()
requireUserPresence optional boolean Ask you to authenticate (with Touch ID, an Apple Watch, or your password) each time the secret is read. Such secrets aren't listed by items(), but can be replaced and removed without authenticating. Defaults to false.
synchronizable optional boolean Sync the secret to your other Macs through iCloud Keychain. Defaults to false. Can't be combined with requireUserPresence.
None
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    hs.keychain.set("TOTP", "github", "JBSWY3DPEHPK3PXP", { label: "GitHub 2FA seed" })
    hs.keychain.set("bank.example.com", "me", "hunter2", { requireUserPresence: true })
} catch (err) {
    console.error(err.message)
}

hs.keychain.get(service, account, reason) -> Promise<string|null>

Read a secret. If it was stored with requireUserPresence, macOS asks you to authenticate first, and the Promise settles once you have.

hs.keychain.get(service, account, reason) -> Promise<string|null>
Name Type Description
service string The service the secret was stored with
account string The account the secret was stored with
reason optional string Why the secret is needed, shown in the authentication prompt, as in "Hammerspoon 2 is trying to reason"
Promise<string|null>
A Promise that resolves to the secret, or null if there's no secret for that service and account, and rejects with an Error if it can't be read (e.g. with code ECANCELED if you cancel the authentication prompt)
hs.keychain.get("TOTP", "github", "show your GitHub code")
    .then(seed => {
        if (seed === null) console.log("No seed stored")
        else console.log(`The seed is ${seed.length} characters long`)
    })
    .catch(err => console.error(err.message))

hs.keychain.remove(service, account) -> boolean

Remove a secret

hs.keychain.remove(service, account) -> boolean
Name Type Description
service string The service the secret was stored with
account string The account the secret was stored with
boolean
true if the secret was removed, false if there was no such secret
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    if (!hs.keychain.remove("TOTP", "github")) console.log("There was no such secret")
} catch (err) {
    console.error(err.message)
}

hs.keychain.items(service) -> Array<object>

List the stored secrets, without the secrets themselves. Secrets stored with requireUserPresence aren't listed, because macOS won't reveal anything about them, not even that they exist, until you authenticate, and listing never asks you to.

hs.keychain.items(service) -> Array<{service: string, account: string, label?: string, comment?: string, created?: Date, modified?: Date, synchronizable: boolean}>
Name Type Description
service optional string Only list the secrets for this service. Lists every secret if omitted.
Array<object>
The stored secrets, sorted by service and then account
Field Type Description
service string
account string
label optional string
comment optional string
created optional Date
modified optional Date
synchronizable boolean
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    const accounts = hs.keychain.items("TOTP").map(item => item.account)
    console.log(`TOTP seeds are stored for: ${accounts.join(", ")}`)
} catch (err) {
    console.error(err.message)
}

hs.keychain.importIdentity(name, path, passphrase) -> None

Store a certificate and its private key (an identity) from a PKCS#12 (.p12) file, replacing any certificates already stored under the same name. Once stored, the private key can be used for TLS, but can't be read back out. The file can be deleted afterwards.

A PKCS#12 file can be exported from Keychain Access, or made from a certificate and key with openssl pkcs12 -export -in cert.pem -inkey key.pem -out identity.p12.

hs.keychain.importIdentity(name, path, passphrase) -> None
Name Type Description
name string The name to store it under, which is how other modules find it. Can't be empty.
path string The path of the PKCS#12 file
passphrase optional string The file's passphrase, if it has one
None
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    hs.keychain.importIdentity("my server", "~/Downloads/server.p12", "the passphrase")
} catch (err) {
    console.error(err.message)
}

hs.keychain.importCertificate(name, path) -> None

Store the certificates in a PEM or DER file, such as a private certificate authority's, so other modules can trust them, replacing any certificates already stored under the same name. A PEM file may hold several certificates, which are all stored under the name.

hs.keychain.importCertificate(name, path) -> None
Name Type Description
name string The name to store them under, which is how other modules find them. Can't be empty.
path string The path of the PEM or DER file
None
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    hs.keychain.importCertificate("home CA", "~/Downloads/ca.pem")
} catch (err) {
    console.error(err.message)
}

hs.keychain.removeCertificate(name) -> boolean

Remove the certificates, and any private key, stored under a name

hs.keychain.removeCertificate(name) -> boolean
Name Type Description
name string The name they were stored under
boolean
true if they were removed, false if nothing was stored under that name
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    if (!hs.keychain.removeCertificate("my server")) console.log("There was no such certificate")
} catch (err) {
    console.error(err.message)
}

hs.keychain.certificates() -> Array<object>

List the stored certificates

hs.keychain.certificates() -> Array<{name: string, subject?: string, expires?: Date, hasPrivateKey: boolean}>
Array<object>
The stored certificates, sorted by name. subject is the certificate's subject, usually its common name, and hasPrivateKey is true for an identity stored with importIdentity().
Field Type Description
name string
subject optional string
expires optional Date
hasPrivateKey boolean
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    for (const cert of hs.keychain.certificates()) {
        console.log(`${cert.name}: ${cert.subject}, expires ${cert.expires}`)
    }
} catch (err) {
    console.error(err.message)
}