Authentication
Sign every /sdk/v1 request with your key, verify the setup, and fix 401 responses.
Every /sdk/v1 request carries four headers that prove it was made with your key's secret. The
signature covers the method, path, body and time, so a captured request cannot be altered or
replayed.
Headers
| Header | Value |
|---|---|
x-key-id | Your key ID, for example nk_live_sRwG9z2hK2hdV4Il83J7Cw |
x-timestamp | Current Unix time in seconds |
x-nonce | A random string of 8–128 characters, new for every request |
x-signature | Base64 HMAC-SHA256 of the canonical string, described below |
Signature
Build the canonical string from six lines joined with \n, with no trailing newline:
NCS1
{HTTP method, uppercase}
{path, without the query string}
{x-timestamp}
{x-nonce}
{SHA-256 of the body, lowercase hex}Then compute:
signingKey = hex(SHA-256(secret))
signature = base64(HMAC-SHA256(signingKey, canonicalString))- Signing key. The lowercase hex SHA-256 of your secret: a 64-character string, used as the HMAC key in its UTF-8 form. Not the secret itself and not the raw digest bytes.
- Signature. Standard Base64 with padding, not Base64URL.
Rules
- Timestamp. Unix seconds. It must be within 300 seconds of the server clock.
- Nonce. 8–128 characters, unique per request. A nonce is accepted once per key within the timestamp window. Generate 16 random bytes and encode them as Base64URL.
- Path. Without scheme, host and query string, exactly as it appears in the request URL,
percent-encoding included. For
GET /sdk/v1/users/u_42/measurements?page=2you sign/sdk/v1/users/u_42/measurements. The query string is not signed. - Body. Hash the exact bytes you send. Serialize the JSON once, hash that string, and send
the same string. For an empty body (every
GET, andPOST /sdk/v1/auth/test) hash the empty string:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. - Content type. Send
Content-Type: application/jsonwith every body. Without it the server reads the body as empty and the signature does not match. - Retries. Sign each attempt again with a new timestamp and nonce.
Signing helpers
Each helper signs a request and returns the data of the response. Later pages reuse them.
Node.js 20 or later, saved as neccessory.js (ES module).
import crypto from 'node:crypto';
const API = 'https://neccessory.com';
const KEY_ID = process.env.NECCESSORY_KEY_ID;
const SECRET = process.env.NECCESSORY_SECRET;
const sha256Hex = (data) => crypto.createHash('sha256').update(data).digest('hex');
export function signHeaders({ keyId, secret, method, path, body = '' }) {
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = crypto.randomBytes(16).toString('base64url');
const canonical = ['NCS1', method.toUpperCase(), path, timestamp, nonce, sha256Hex(body)].join('\n');
const signature = crypto.createHmac('sha256', sha256Hex(secret)).update(canonical).digest('base64');
return {
'x-key-id': keyId,
'x-timestamp': timestamp,
'x-nonce': nonce,
'x-signature': signature,
};
}
export async function neccessory(method, pathWithQuery, payload) {
const path = pathWithQuery.split('?')[0];
const body = payload === undefined ? '' : JSON.stringify(payload);
const headers = signHeaders({ keyId: KEY_ID, secret: SECRET, method, path, body });
if (body) headers['content-type'] = 'application/json';
const res = await fetch(API + pathWithQuery, { method, headers, body: body || undefined });
const json = await res.json();
if (!json.ok) {
const requestId = res.headers.get('x-request-id');
throw Object.assign(new Error(`${json.error.code}: ${json.error.message} (${requestId})`), {
status: res.status,
code: json.error.code,
requestId,
});
}
return json.data;
}import { neccessory } from './neccessory.js';
const key = await neccessory('POST', '/sdk/v1/auth/test');
console.log(key.keyId, key.mode);Python 3.9 or later with requests.
import base64
import hashlib
import hmac
import json
import os
import secrets
import time
import requests
API = "https://neccessory.com"
KEY_ID = os.environ["NECCESSORY_KEY_ID"]
SECRET = os.environ["NECCESSORY_SECRET"]
def sign_headers(key_id: str, secret: str, method: str, path: str, body: bytes = b"") -> dict:
timestamp = str(int(time.time()))
nonce = secrets.token_urlsafe(16)
canonical = "\n".join(
["NCS1", method.upper(), path, timestamp, nonce, hashlib.sha256(body).hexdigest()]
)
signing_key = hashlib.sha256(secret.encode()).hexdigest().encode()
digest = hmac.new(signing_key, canonical.encode(), hashlib.sha256).digest()
return {
"x-key-id": key_id,
"x-timestamp": timestamp,
"x-nonce": nonce,
"x-signature": base64.b64encode(digest).decode(),
}
def neccessory(method: str, path: str, payload=None, params=None):
body = b"" if payload is None else json.dumps(payload, separators=(",", ":")).encode()
headers = sign_headers(KEY_ID, SECRET, method, path, body)
if body:
headers["content-type"] = "application/json"
res = requests.request(
method, API + path, params=params, data=body or None, headers=headers, timeout=30
)
envelope = res.json()
if not envelope["ok"]:
error = envelope["error"]
request_id = res.headers.get("x-request-id")
raise RuntimeError(f'{error["code"]}: {error["message"]} ({request_id})')
return envelope["data"]
if __name__ == "__main__":
key = neccessory("POST", "/sdk/v1/auth/test")
print(key["keyId"], key["mode"])Pass query parameters through params, so they stay out of the signed path. The body is
serialized once and the same bytes are hashed and sent.
Server-side Swift or tooling, with CryptoKit. Never ship the secret inside an app.
import CryptoKit
import Foundation
struct NeccessorySigner {
let keyId: String
let secret: String
func sign(_ request: inout URLRequest) {
let method = (request.httpMethod ?? "GET").uppercased()
let components = request.url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false) }
let path = components?.percentEncodedPath ?? "/"
let body = request.httpBody ?? Data()
let timestamp = String(Int(Date().timeIntervalSince1970))
let nonce = UUID().uuidString
let canonical = ["NCS1", method, path, timestamp, nonce, Self.sha256Hex(body)]
.joined(separator: "\n")
let signingKey = SymmetricKey(data: Data(Self.sha256Hex(Data(secret.utf8)).utf8))
let mac = HMAC<SHA256>.authenticationCode(for: Data(canonical.utf8), using: signingKey)
request.setValue(keyId, forHTTPHeaderField: "x-key-id")
request.setValue(timestamp, forHTTPHeaderField: "x-timestamp")
request.setValue(nonce, forHTTPHeaderField: "x-nonce")
request.setValue(Data(mac).base64EncodedString(), forHTTPHeaderField: "x-signature")
if !body.isEmpty {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
}
private static func sha256Hex(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
}
let environment = ProcessInfo.processInfo.environment
let signer = NeccessorySigner(
keyId: environment["NECCESSORY_KEY_ID"]!,
secret: environment["NECCESSORY_SECRET"]!
)
var request = URLRequest(url: URL(string: "https://neccessory.com/sdk/v1/auth/test")!)
request.httpMethod = "POST"
signer.sign(&request)
let (data, _) = try await URLSession.shared.data(for: request)
print(String(decoding: data, as: UTF8.self))Set httpBody before calling sign, so the signature covers the bytes you send.
Verify your key
POST /sdk/v1/auth/test with an empty body confirms that signing works and returns the key's
settings.
{
"ok": true,
"data": {
"keyId": "nk_live_sRwG9z2hK2hdV4Il83J7Cw",
"status": "active",
"mode": "cloud",
"features": ["hrv", "bp"],
"rateLimitPerMin": 0,
"quotaSecondsMonth": 36000,
"tokenQuotaMonth": null,
"tokenBalance": 1453000,
"organizationId": "org_4c1e9b7a2d0f5836e1a7b4c9",
"serverTime": 1790000000123
}
}| Field | Type | Description |
|---|---|---|
keyId | string | The key that signed the request |
status | string | active. Disabled and expired keys fail signing with 401 |
mode | string | cloud, on_device or test |
features | string[] | null | Metric sets the key may request. null allows all sets |
rateLimitPerMin | number | Per-key request limit. 0 means no limit |
quotaSecondsMonth | number | null | Monthly quota of cloud seconds. null means no quota |
tokenQuotaMonth | number | null | Monthly spend cap in tokens. null means no cap |
tokenBalance | number | null | Your organization's token balance |
organizationId | string | null | Organization that owns the key |
serverTime | number | Server clock, epoch milliseconds. Compare it with your clock to detect skew |
Troubleshooting 401
Every authentication failure returns the same response: 401 with
error.code: "unauthorized". The exact reason is recorded as errorCode in the
usage log. Read it with GET /sdk/v1/logs, or paste the call's
X-Request-Id into the console search.
errorCode | Cause | Fix |
|---|---|---|
missing_credentials | One of the four headers is missing | Send all four. Check that no proxy strips custom headers |
invalid_nonce | The nonce is shorter than 8 or longer than 128 characters | Generate 16 random bytes and encode them as Base64URL |
invalid_timestamp | x-timestamp is not a number | Send Unix seconds as an integer string |
timestamp_out_of_window | The timestamp is more than 300 s from the server clock | Send seconds, not milliseconds. Sync the clock with NTP and compare with serverTime |
unknown_key | No key has this key ID | Copy the key ID from Console → Keys. Check that you use the key of the right environment |
key_disabled | The key is disabled | Enable it in the console or use another key |
key_expired | The key is past its expiry date | Create a new key |
invalid_signature | The signature does not match | Check the rules above: signing key is the hex SHA-256 of the secret, the path has no host or query, the body hash covers the exact bytes sent, Content-Type is application/json, the signature is standard Base64 |
nonce_reused | The nonce was already used within the window | Generate a new nonce for every request, including retries |
A refused call appears in your log only when its x-key-id names one of your keys. If a 401
has no matching log row, the key ID is missing or wrong.
Keep the secret on your server
The secret signs any request for your key, including reads of every measurement it stored. Keep it in server-side configuration, never in a web page, an app or a repository. If it leaks, rotate the key in the console.
Test keys
A test key (nk_test_…) signs exactly like a live key. It returns deterministic synthetic
results marked "test": true, is never billed, and cannot mint on-device model grants. Use it
in CI and staging; see API keys.