הפונקציה חותמת על כל בקשה, ובודקת את החתימה של כל תשובה. כל שאר הדוגמאות משתמשות בה. ההסבר המלא נמצא באימות וחתימות.
#!/usr/bin/env bash
# SibLinks API from the shell (bash, curl, openssl, jq).
# Note: openssl receives the secret as an argument, so other users on the same machine can see it
# in the process list. Use this for testing; in production use one of the language clients.
set -euo pipefail
BASE_URL="${SIBLINKS_BASE_URL:-https://api.siblinks.co.il}"
hmac_hex() { openssl dgst -sha256 -hmac "$SIBLINKS_SECRET" -r | cut -d' ' -f1; }
# siblinks_call METHOD PATH [BODY_JSON]: prints the verified response body.
siblinks_call() {
local method="$1" path="$2" body="${3-}"
local ts nonce sig tmp status expected got
ts=$(date +%s)
nonce=$(openssl rand -hex 16)
sig=$(printf '%s\n%s\n%s\n%s\n%s' "$ts" "$method" "$path" \
"$(printf '%s' "$body" | openssl dgst -sha256 -r | cut -d' ' -f1)" "$nonce" | hmac_hex)
tmp=$(mktemp -d)
local args=(-sS -X "$method" "$BASE_URL$path" --compressed -D "$tmp/headers" -o "$tmp/body" -w '%{http_code}'
-H "X-Site-Id: $SIBLINKS_SITE_ID" -H "X-Timestamp: $ts" -H "X-Nonce: $nonce" -H "X-Signature: $sig")
if [ -n "$body" ]; then
args+=(-H "Content-Type: application/json" --data-binary "$body")
fi
status=$(curl "${args[@]}")
expected=$(printf 'response\n%s\n%s\n%s' "$sig" "$status" \
"$(openssl dgst -sha256 -r < "$tmp/body" | cut -d' ' -f1)" | hmac_hex)
got=$( (grep -i '^x-siblinks-signature:' "$tmp/headers" || true) | tail -1 | cut -d: -f2 | tr -d ' \r' | tr 'A-F' 'a-f')
if [ "$status" -lt 400 ] && [ "$expected" != "$got" ]; then
echo "unsigned_response" >&2; rm -rf "$tmp"; return 1 # never trust it
fi
if [ "$status" -ge 400 ]; then
echo "error $status $(jq -r '.error.code // "unknown"' "$tmp/body")" >&2; rm -rf "$tmp"; return 1
fi
cat "$tmp/body"
rm -rf "$tmp"
}
import hashlib
import hmac
import json
import os
import secrets
import time
import requests
BASE_URL = os.environ.get("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = os.environ["SIBLINKS_SITE_ID"]
SECRET = os.environ["SIBLINKS_SECRET"]
class SibLinksError(Exception):
def __init__(self, status, code):
super().__init__(f"{status} {code}")
self.status, self.code = status, code
def _hmac(text: str) -> str:
return hmac.new(SECRET.encode("utf-8"), text.encode("utf-8"), hashlib.sha256).hexdigest()
def call(method: str, path: str, body=None):
raw = b"" if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
ts = str(int(time.time()))
nonce = secrets.token_hex(16)
signature = _hmac(f"{ts}\n{method}\n{path}\n{hashlib.sha256(raw).hexdigest()}\n{nonce}")
headers = {"X-Site-Id": SITE_ID, "X-Timestamp": ts, "X-Nonce": nonce, "X-Signature": signature}
if body is not None:
headers["Content-Type"] = "application/json"
r = requests.request(method, BASE_URL + path, data=raw if body is not None else None,
headers=headers, timeout=30)
expected = _hmac(f"response\n{signature}\n{r.status_code}\n{hashlib.sha256(r.content).hexdigest()}")
signed = hmac.compare_digest(expected, r.headers.get("X-SibLinks-Signature", "").lower())
if r.status_code < 400 and not signed:
raise SibLinksError(r.status_code, "unsigned_response") # never trust it
data = r.json()
if r.status_code >= 400:
raise SibLinksError(r.status_code, (data.get("error") or {}).get("code", "unknown"))
return data
// SibLinks API client example (Node.js 18+, no dependencies).
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
const BASE_URL = process.env.SIBLINKS_BASE_URL || 'https://api.siblinks.co.il';
const SITE_ID = process.env.SIBLINKS_SITE_ID;
const SECRET = process.env.SIBLINKS_SECRET;
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const hmac = (text) => createHmac('sha256', SECRET).update(text, 'utf8').digest('hex');
export async function call(method, path, body) {
const raw = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body), 'utf8');
const ts = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString('hex');
const signature = hmac(`${ts}\n${method}\n${path}\n${sha256(raw)}\n${nonce}`);
const headers = { 'X-Site-Id': SITE_ID, 'X-Timestamp': ts, 'X-Nonce': nonce, 'X-Signature': signature };
if (body !== undefined) headers['Content-Type'] = 'application/json';
const res = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : raw });
const resBody = Buffer.from(await res.arrayBuffer());
const expected = Buffer.from(hmac(`response\n${signature}\n${res.status}\n${sha256(resBody)}`));
const got = Buffer.from((res.headers.get('x-siblinks-signature') || '').toLowerCase());
const signedOk = got.length === expected.length && timingSafeEqual(got, expected);
if (res.status < 400 && !signedOk) throw new Error('unsigned_response'); // never trust it
const data = JSON.parse(resBody.toString('utf8'));
if (res.status >= 400) throw Object.assign(new Error(data.error?.code || 'unknown'), { status: res.status });
return data;
}
<?php
// SibLinks API client example (PHP 8, curl extension).
$base_url = getenv( 'SIBLINKS_BASE_URL' ) ?: 'https://api.siblinks.co.il';
$site_id = getenv( 'SIBLINKS_SITE_ID' );
$secret = getenv( 'SIBLINKS_SECRET' );
function siblinks_call( string $method, string $path, ?array $body = null ): array {
global $base_url, $site_id, $secret;
$raw = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE );
$ts = (string) time();
$nonce = bin2hex( random_bytes( 16 ) );
$sig = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $secret );
$headers = array( "X-Site-Id: {$site_id}", "X-Timestamp: {$ts}", "X-Nonce: {$nonce}", "X-Signature: {$sig}" );
if ( null !== $body ) {
$headers[] = 'Content-Type: application/json';
}
$resp_sig = '';
$ch = curl_init( $base_url . $path );
curl_setopt_array(
$ch,
array(
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '', // decode gzip/br if a proxy compressed the response
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADERFUNCTION => function ( $ch, $line ) use ( &$resp_sig ) {
if ( 0 === stripos( $line, 'X-SibLinks-Signature:' ) ) {
$resp_sig = strtolower( trim( substr( $line, 21 ) ) );
}
return strlen( $line );
},
)
);
if ( null !== $body ) {
curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw );
}
$resp = curl_exec( $ch );
$status = (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
if ( false === $resp ) {
throw new RuntimeException( 'connection_failed: ' . curl_error( $ch ) );
}
$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $secret );
if ( $status < 400 && ! hash_equals( $expected, $resp_sig ) ) {
throw new RuntimeException( 'unsigned_response' ); // never trust it
}
$data = json_decode( $resp, true );
if ( $status >= 400 ) {
throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
}
return $data;
}
<?php
// SibLinks API client example (PHP 8.0+, Guzzle 7: composer require guzzlehttp/guzzle).
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
final class SibLinksClient {
private Client $http;
public function __construct( private string $site_id, private string $secret, string $base_url = 'https://api.siblinks.co.il' ) {
$this->http = new Client(
array(
'base_uri' => $base_url,
'timeout' => 30,
'http_errors' => false, // errors are read from the JSON body below
)
);
}
public function call( string $method, string $path, ?array $body = null ): array {
$raw = null === $body ? '' : json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR );
$ts = (string) time();
$nonce = bin2hex( random_bytes( 16 ) );
$sig = hash_hmac( 'sha256', "{$ts}\n{$method}\n{$path}\n" . hash( 'sha256', $raw ) . "\n{$nonce}", $this->secret );
$headers = array(
'X-Site-Id' => $this->site_id,
'X-Timestamp' => $ts,
'X-Nonce' => $nonce,
'X-Signature' => $sig,
);
if ( null !== $body ) {
$headers['Content-Type'] = 'application/json';
}
$res = $this->http->request( $method, $path, array( 'headers' => $headers, 'body' => $raw ) );
$status = $res->getStatusCode();
$resp = (string) $res->getBody();
$expected = hash_hmac( 'sha256', "response\n{$sig}\n{$status}\n" . hash( 'sha256', $resp ), $this->secret );
if ( $status < 400 && ! hash_equals( $expected, strtolower( $res->getHeaderLine( 'X-SibLinks-Signature' ) ) ) ) {
throw new RuntimeException( 'unsigned_response' ); // never trust it
}
$data = json_decode( $resp, true );
if ( $status >= 400 ) {
throw new RuntimeException( $data['error']['code'] ?? 'unknown', $status );
}
return $data;
}
}
// SibLinks API client example (Java 17+, Jackson 2.x: com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SibLinksClient {
static final String BASE_URL = Optional.ofNullable(System.getenv("SIBLINKS_BASE_URL")).orElse("https://api.siblinks.co.il");
static final String SITE_ID = System.getenv("SIBLINKS_SITE_ID");
static final String SECRET = System.getenv("SIBLINKS_SECRET");
static final ObjectMapper JSON = new ObjectMapper();
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final SecureRandom RANDOM = new SecureRandom();
static final HexFormat HEX = HexFormat.of();
static class SibLinksException extends Exception {
final int status;
final String code;
SibLinksException(int status, String code) {
super(status + " " + code);
this.status = status;
this.code = code;
}
}
static String sha256(byte[] data) throws Exception {
return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(data));
}
static String hmac(String message) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return HEX.formatHex(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
}
static JsonNode call(String method, String path, Object body) throws Exception {
byte[] raw = body == null ? new byte[0] : JSON.writeValueAsBytes(body);
String ts = Long.toString(System.currentTimeMillis() / 1000);
byte[] nonceBytes = new byte[16];
RANDOM.nextBytes(nonceBytes);
String nonce = HEX.formatHex(nonceBytes);
String signature = hmac(ts + "\n" + method + "\n" + path + "\n" + sha256(raw) + "\n" + nonce);
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.timeout(Duration.ofSeconds(30))
.header("X-Site-Id", SITE_ID)
.header("X-Timestamp", ts)
.header("X-Nonce", nonce)
.header("X-Signature", signature)
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(raw));
if (body != null) {
req.header("Content-Type", "application/json");
}
HttpResponse<byte[]> res = HTTP.send(req.build(), HttpResponse.BodyHandlers.ofByteArray());
int status = res.statusCode();
String expected = hmac("response\n" + signature + "\n" + status + "\n" + sha256(res.body()));
String got = res.headers().firstValue("X-SibLinks-Signature").orElse("").toLowerCase(Locale.ROOT);
boolean signed = MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), got.getBytes(StandardCharsets.UTF_8));
if (status < 400 && !signed) {
throw new SibLinksException(status, "unsigned_response"); // never trust it
}
JsonNode data = JSON.readTree(res.body());
if (status >= 400) {
throw new SibLinksException(status, data.path("error").path("code").asText("unknown"));
}
return data;
}
// main() and your own code go here
}
// SibLinks API client example (.NET 6+, no extra packages).
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
public class SibLinksException : Exception
{
public int Status { get; }
public string Code { get; }
public SibLinksException(int status, string code) : base($"{status} {code}")
{
Status = status;
Code = code;
}
}
public static class SibLinks
{
static readonly string BaseUrl = Environment.GetEnvironmentVariable("SIBLINKS_BASE_URL") ?? "https://api.siblinks.co.il";
static readonly string SiteId = Environment.GetEnvironmentVariable("SIBLINKS_SITE_ID")!;
static readonly byte[] Secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SIBLINKS_SECRET")!);
static readonly HttpClient Http = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All })
{
Timeout = TimeSpan.FromSeconds(30),
};
static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();
static string Hmac(string message) => Hex(HMACSHA256.HashData(Secret, Encoding.UTF8.GetBytes(message)));
public static async Task<JsonNode> Call(string method, string path, object? body = null)
{
byte[] raw = body is null ? Array.Empty<byte>() : JsonSerializer.SerializeToUtf8Bytes(body);
string ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
string nonce = Hex(RandomNumberGenerator.GetBytes(16));
string signature = Hmac($"{ts}\n{method}\n{path}\n{Hex(SHA256.HashData(raw))}\n{nonce}");
using var req = new HttpRequestMessage(new HttpMethod(method), BaseUrl + path);
req.Headers.Add("X-Site-Id", SiteId);
req.Headers.Add("X-Timestamp", ts);
req.Headers.Add("X-Nonce", nonce);
req.Headers.Add("X-Signature", signature);
if (body is not null)
{
req.Content = new ByteArrayContent(raw);
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
using var res = await Http.SendAsync(req);
byte[] resBody = await res.Content.ReadAsByteArrayAsync();
int status = (int)res.StatusCode;
string expected = Hmac($"response\n{signature}\n{status}\n{Hex(SHA256.HashData(resBody))}");
string got = res.Headers.TryGetValues("X-SibLinks-Signature", out var values) ? values.First().ToLowerInvariant() : "";
bool signed = CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(got));
if (status < 400 && !signed)
{
throw new SibLinksException(status, "unsigned_response"); // never trust it
}
JsonNode data = JsonNode.Parse(resBody)!;
if (status >= 400)
{
throw new SibLinksException(status, data["error"]?["code"]?.GetValue<string>() ?? "unknown");
}
return data;
}
}
// SibLinks API client example (Go 1.20+, standard library only).
package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var (
baseURL = envOr("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
siteID = os.Getenv("SIBLINKS_SITE_ID")
secret = os.Getenv("SIBLINKS_SECRET")
httpClient = &http.Client{Timeout: 30 * time.Second}
)
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func sha256Hex(b []byte) string {
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
func hmacHex(message string) string {
m := hmac.New(sha256.New, []byte(secret))
m.Write([]byte(message))
return hex.EncodeToString(m.Sum(nil))
}
// APIError is an error answered by the API ({"error": {"code": ...}}).
type APIError struct {
Status int
Code string
}
func (e *APIError) Error() string { return fmt.Sprintf("%d %s", e.Status, e.Code) }
// call sends a signed request and returns the verified JSON response.
func call(method, path string, body any) (map[string]any, error) {
var raw []byte
if body != nil {
var err error
if raw, err = json.Marshal(body); err != nil {
return nil, err
}
}
ts := strconv.FormatInt(time.Now().Unix(), 10)
nonceBytes := make([]byte, 16)
if _, err := rand.Read(nonceBytes); err != nil {
return nil, err
}
nonce := hex.EncodeToString(nonceBytes)
signature := hmacHex(ts + "\n" + method + "\n" + path + "\n" + sha256Hex(raw) + "\n" + nonce)
req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(raw))
if err != nil {
return nil, err
}
req.Header.Set("X-Site-Id", siteID)
req.Header.Set("X-Timestamp", ts)
req.Header.Set("X-Nonce", nonce)
req.Header.Set("X-Signature", signature)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
resBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
expected := hmacHex("response\n" + signature + "\n" + strconv.Itoa(resp.StatusCode) + "\n" + sha256Hex(resBody))
got := strings.ToLower(resp.Header.Get("X-SibLinks-Signature"))
if resp.StatusCode < 400 && !hmac.Equal([]byte(expected), []byte(got)) {
return nil, &APIError{resp.StatusCode, "unsigned_response"} // never trust it
}
var data map[string]any
if err := json.Unmarshal(resBody, &data); err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
code := "unknown"
if e, ok := data["error"].(map[string]any); ok {
if c, ok := e["code"].(string); ok {
code = c
}
}
return nil, &APIError{resp.StatusCode, code}
}
return data, nil
}
# SibLinks API client example (Ruby 3.0+, standard library only).
require "json"
require "net/http"
require "openssl"
require "securerandom"
BASE_URL = ENV.fetch("SIBLINKS_BASE_URL", "https://api.siblinks.co.il")
SITE_ID = ENV.fetch("SIBLINKS_SITE_ID")
SECRET = ENV.fetch("SIBLINKS_SECRET")
class SibLinksError < StandardError
attr_reader :status, :code
def initialize(status, code)
super("#{status} #{code}")
@status = status
@code = code
end
end
def hmac_hex(message)
OpenSSL::HMAC.hexdigest("SHA256", SECRET, message)
end
def call(method, path, body = nil)
raw = body.nil? ? "" : JSON.generate(body)
ts = Time.now.to_i.to_s
nonce = SecureRandom.hex(16)
signature = hmac_hex("#{ts}\n#{method}\n#{path}\n#{OpenSSL::Digest::SHA256.hexdigest(raw)}\n#{nonce}")
uri = URI(BASE_URL + path)
req = method == "GET" ? Net::HTTP::Get.new(uri) : Net::HTTP::Post.new(uri)
req["X-Site-Id"] = SITE_ID
req["X-Timestamp"] = ts
req["X-Nonce"] = nonce
req["X-Signature"] = signature
unless body.nil?
req["Content-Type"] = "application/json"
req.body = raw
end
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) { |http| http.request(req) }
status = res.code.to_i
res_body = res.body.to_s
expected = hmac_hex("response\n#{signature}\n#{status}\n#{OpenSSL::Digest::SHA256.hexdigest(res_body)}")
signed = OpenSSL.secure_compare(expected, res["X-SibLinks-Signature"].to_s.downcase)
raise SibLinksError.new(status, "unsigned_response") if status < 400 && !signed # never trust it
data = JSON.parse(res_body)
raise SibLinksError.new(status, data.dig("error", "code") || "unknown") if status >= 400
data
end