Vis-CAT 
The Visual Cognition Assessment Tool
  • Home
  • About Us
  • News & Updates
  • Early Intervention
  • Contact Us
  • Parents
  • Teachers
  • Research Foundations
  • Press Releases
  • FAQ
  • Vis-CAT Developer Guide
  • More
    • Home
    • About Us
    • News & Updates
    • Early Intervention
    • Contact Us
    • Parents
    • Teachers
    • Research Foundations
    • Press Releases
    • FAQ
    • Vis-CAT Developer Guide
Vis-CAT 
The Visual Cognition Assessment Tool
  • Home
  • About Us
  • News & Updates
  • Early Intervention
  • Contact Us
  • Parents
  • Teachers
  • Research Foundations
  • Press Releases
  • FAQ
  • Vis-CAT Developer Guide

Vis-CAT Partner API

Overview

The VisCAT Partner API lets your system enrol a child for a VisCAT assessment with one HTTPS call. You get back a unique test link to email to your client.


We suggest that the email to your client also includes a QR Code of the link in addition to the link itself that can be scanned by an iPad or similar large format touch screen device.

When the child completes the test, VisCAT emails the PDF report to the contact you supplied.


The API has exactly one operation: POST /v2/partner/candidate. Your credential can call nothing else. Every other route returns 403.

Each environment has its own credential. A test credential does not work against production, and the reverse.

An integration has three steps:

  1. Log in. Exchange your user ID and secret for a short-lived ID token (a JWT), using AWS Cognito.
  2. Call the API. Send the ID token as Authorization: Bearer <token> on each request.
  3. Keep the session alive. Use the refresh token to get a new ID token before the old one expires. Log in again when the refresh token itself expires.

Your credentials


VisCAT sends your user ID and will provide the secret to you via SMS to your private phone. They are the username and password of a service account in VisCAT's AWS Cognito user pool. The user ID looks like api-<32 hex characters>-<8 hex characters>@partner.viscat.invalid.

You also need these values to log in. They are not secret, and VisCAT supplies them for each environment:

 

Handle the secret like any production password:

  • Store it in a secrets manager or an encrypted environment variable. Never commit it to source control or write it to logs.
  • Delete the SMS once you have stored the secret. VisCAT does not keep a copy and cannot send it again.
  • If the secret is lost or exposed, ask VisCAT to rotate it. Rotation issues a new secret for the same user ID, and the old secret stops working at once.

There is no client secret. The app client is public, so you log in with the user ID and secret alone.


Logging in and using the JWT


You log in with AWS Cognito, not with the VisCAT API. Cognito returns three tokens. You send only the ID token to VisCAT.


Log in with SRP


The user pool accepts only the Secure Remote Password (SRP) login flow. SRP proves you know the secret without sending it over the network. The plain password flow (USER_PASSWORD_AUTH) is turned off and returns an error.


Do not change the flow in your client library. Leave AWS Amplify's authFlowType and amazon-cognito-identity-js's setAuthenticationFlowType at their default, USER_SRP_AUTH. USER_PASSWORD_AUTH and ADMIN_USER_PASSWORD_AUTH are both turned off.

The AWS CLI and API tools such as Postman cannot run SRP. To get an ID token for manual testing, run one of the examples below and print the token it gets.

SRP takes two calls to the Cognito endpoint https://cognito-idp.ap-southeast-2.amazonaws.com/:

  1. InitiateAuth with AuthFlow: USER_SRP_AUTH, your user ID and a public value SRP_A. Cognito replies with a PASSWORD_VERIFIER challenge.
  2. RespondToAuthChallenge with a signature computed from the challenge and your secret. Cognito replies with an AuthenticationResult.

You do not need to write the SRP maths yourself in JavaScript or Python. The libraries in the examples below do it for you. Java has no maintained SRP library, so the Java example includes a small helper.


A successful login returns:

 

Send the JWT


Put the ID token in the Authorization header of every API request:

POST /v2/partner/candidate HTTP/1.1
Host: api.admin.viscat.com.au
Authorization: Bearer eyJraWQiOiJ...
Content-Type: application/json

Three rules catch most first-time integrations:

  • Send the IdToken, not the AccessToken. VisCAT accepts ID tokens only. An access token gets a bare 401 with no explanation.
  • Do not send an x-organisation-id header. Your organisation comes from your credential. Sending the header returns 400.
  • Reuse the token. Log in once and use the same ID token for every call until it nears expiry. Logging in before each request is slow and can hit Cognito's rate limits.


Keeping the session alive


An ID token lasts 60 minutes, and the refresh token that renews it lasts 6 hours. So a long-running integration refreshes about once an hour and logs in again with SRP about every 6 hours.

[embed: node/4700ef0e-6f3b]andle the secret like any production password:

  • Store it in a secrets manager or an encrypted environment variable. Never commit it to source control or write it to logs.
  • Delete the SMS once you have stored the secret. VisCAT does not keep a copy and cannot send it again.
  • If the secret is lost or exposed, ask VisCAT to rotate it. Rotation issues a new secret for the same user ID, and the old secret stops working at once.

There is no client secret. The app client is public, so you log in with the user ID and secret alone.


Logging in and using the JWT


You log in with AWS Cognito, not with the VisCAT API. Cognito returns three tokens. You send only the ID token to VisCAT.


Log in with SRP


The user pool accepts only the Secure Remote Password (SRP) login flow. SRP proves you know the secret without sending it over the network. The plain password flow (USER_PASSWORD_AUTH) is turned off and returns an error.


Do not change the flow in your client library. Leave AWS Amplify's authFlowType and amazon-cognito-identity-js's setAuthenticationFlowType at their default, USER_SRP_AUTH. USER_PASSWORD_AUTH and ADMIN_USER_PASSWORD_AUTH are both turned off.

The AWS CLI and API tools such as Postman cannot run SRP. To get an ID token for manual testing, run one of the examples below and print the token it gets.

SRP takes two calls to the Cognito endpoint https://cognito-idp.ap-southeast-2.amazonaws.com/:

  1. InitiateAuth with AuthFlow: USER_SRP_AUTH, your user ID and a public value SRP_A. Cognito replies with a PASSWORD_VERIFIER challenge.
  2. RespondToAuthChallenge with a signature computed from the challenge and your secret. Cognito replies with an AuthenticationResult.

You do not need to write the SRP maths yourself in JavaScript or Python. The libraries in the examples below do it for you. Java has no maintained SRP library, so the Java example includes a small helper.


A successful login returns:

  

Each request checks the ID token first. A failed refresh means the 6-hour refresh token has run out, so the token manager logs in with SRP again.


Refresh before the ID token expires


Refreshing needs no secret and no SRP. Call Cognito InitiateAuth with:

{
 "AuthFlow": "REFRESH_TOKEN_AUTH",
 "ClientId": "<app client ID>",
 "AuthParameters": { "REFRESH_TOKEN": "<refresh token from login>" }
}

Cognito returns a new IdToken and AccessToken, valid for another 60 minutes. It does not return a new refresh token. Keep using the one from your last login.

The refresh token's 6 hours run from the SRP login, and refreshing does not extend them. Once they are up, refresh fails with NotAuthorizedException, and you must log in with SRP again.


Recommended pattern


Wrap token handling in one small token manager, as the examples below do. Before each API call it:

  1. Logs in with SRP if it holds no tokens yet.
  2. Reads the ID token's exp claim. If fewer than 5 minutes remain, it refreshes.
  3. Logs in with SRP again if the refresh fails with NotAuthorizedException.

If the API still answers 401, get a fresh token once and retry the request once. Do not loop. A second 401 means something else is wrong.

You do not need a background timer. Checking the token just before each call is enough, even after long idle periods.


When logging in again will not help

  

VisCAT checks that your credential is still active on every request. A revoke takes effect at once, even while your ID token has time left. Repeated failed logins can lock the account for a while, so do not retry a rejected secret in a loop.


API reference


POST /v2/partner/candidate


Creates one candidate in your organisation and returns the link the child uses to take the test. When the test is complete, VisCAT emails the PDF report to reportContact.email.

 

JSON
{
 "firstName": "Joshua",
 "lastName": "El Khoury",
 "DoB": "2016-12-10",
 "reportContact": { "email": "parent@example.com", "name": "Jane El Khoury" },
 "customerId": "CUST-000123"
}

Response: 201 Created

{
 "candidateId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
 "test_url": "https://<candidate site>/?testUID=3eXwSS9Ugi9D6PkICJgZX0DwdRqLFlCJc6Q3fGgO45EVUpPgLaIfayBuw6zDEb5M1Pv7xVsRI4C4iUy6apdpZBPF",
 "customerId": "CUST-000123"
}

  • candidateId is VisCAT's ID for the candidate. Store it beside your customerId.
  • test_url is the link to give the family. Open it in a browser to start the test.
  • customerId is echoed back so you can match the response to your record.
  • The report contact is never returned.


Errors

Error bodies are JSON with a single message field, for example {"message": "Candidate already exists"}.

 There is no update through the partner API. A 409 means the child is already enrolled. To change the report contact of an existing candidate, contact VisCAT.

Rate limit. Each source IP address may make 500 requests per 15 minutes. Responses carry the standard RateLimit and RateLimit-Policy headers.

Example code

 

Each example is a complete program. It logs in, keeps the token fresh and creates one candidate. All three read the same four environment variables: VISCAT_USER_POOL_ID, VISCAT_CLIENT_ID, VISCAT_USER_ID and VISCAT_SECRET. They point at the test environment. Change the base URL for production.


Keep one token manager for the life of your process and share it between requests. Do not create a new one per call.


JavaScript (Node.js)


Uses amazon-cognito-identity-js, which runs SRP for you.

 

JavaScript 
// Node.js 18+.  npm install amazon-cognito-identity-js
const {
 CognitoUserPool,
 CognitoUser,
 AuthenticationDetails,
} = require('amazon-cognito-identity-js');

const config = {
 apiBaseUrl: 'https://test.api.admin.viscat.com.au',
 userPoolId: process.env.VISCAT_USER_POOL_ID, // e.g. ap-southeast-2_AbCdEfGhI
 clientId: process.env.VISCAT_CLIENT_ID,
 userId: process.env.VISCAT_USER_ID, // from the SMS
 secret: process.env.VISCAT_SECRET, // from the SMS
};

const REFRESH_MARGIN_SECONDS = 300; // refresh when less than 5 minutes remain

class VisCatTokenManager {
 constructor(cfg) {
   this.cfg = cfg;
   const pool = new CognitoUserPool({ UserPoolId: cfg.userPoolId, ClientId: cfg.clientId });
   this.user = new CognitoUser({ Username: cfg.userId, Pool: pool });
   this.session = null;
 }

 // SRP login. amazon-cognito-identity-js uses USER_SRP_AUTH by default.
 login() {
   const details = new AuthenticationDetails({
     Username: this.cfg.userId,
     Password: this.cfg.secret,
   });
   return new Promise((resolve, reject) => {
     this.user.authenticateUser(details, {
       onSuccess: (session) => {
         this.session = session;
         resolve();
       },
       onFailure: reject,
       newPasswordRequired: () =>
         reject(new Error('Unexpected NEW_PASSWORD_REQUIRED challenge. Contact VisCAT.')),
     });
   });
 }

 // REFRESH_TOKEN_AUTH. Keeps the existing refresh token.
 refresh() {
   return new Promise((resolve, reject) => {
     this.user.refreshSession(this.session.getRefreshToken(), (err, session) => {
       if (err) return reject(err);
       this.session = session;
       resolve();
     });
   });
 }

 async getIdToken() {
   if (!this.session) {
     await this.login();
   } else {
     const secondsLeft = this.session.getIdToken().getExpiration() - Date.now() / 1000;
     if (secondsLeft < REFRESH_MARGIN_SECONDS) {
       try {
         await this.refresh();
       } catch (err) {
         if (err.code !== 'NotAuthorizedException') throw err;
         await this.login(); // the 6-hour refresh token has expired
       }
     }
   }
   return this.session.getIdToken().getJwtToken();
 }

 // Call after a 401 to force a new login on the next getIdToken().
 forceRenew() {
   this.session = null;
 }
}

async function createCandidate(tokens, candidate) {
 const send = async () =>
   fetch(`${config.apiBaseUrl}/v2/partner/candidate`, {
     method: 'POST',
     headers: {
       Authorization: `Bearer ${await tokens.getIdToken()}`,
       'Content-Type': 'application/json',
     },
     body: JSON.stringify(candidate),
   });

 let res = await send();
 if (res.status === 401) {
   tokens.forceRenew(); // retry once with a fresh token
   res = await send();
 }
 const body = await res.json();
 if (res.status !== 201) {
   throw new Error(`VisCAT ${res.status}: ${body.message}`);
 }
 return body; // { candidateId, test_url, customerId }
}

async function main() {
 const tokens = new VisCatTokenManager(config);
 const created = await createCandidate(tokens, {
   firstName: 'Joshua',
   lastName: 'El Khoury',
   DoB: '2016-12-10',
   reportContact: { email: 'parent@example.com', name: 'Jane El Khoury' },
   customerId: 'CUST-000123',
 });
 console.log(`Candidate ${created.candidateId}: ${created.test_url}`);
}

main().catch((err) => {
 console.error(err.message);
 process.exit(1);
});

 

Python

Uses pycognito for SRP and boto3 for the refresh. Neither needs AWS credentials.
 

# Python 3.9+.  pip install boto3 pycognito requests
import base64
import json
import os
import time

import boto3
import requests
from pycognito.aws_srp import AWSSRP

API_BASE_URL = "https://test.api.admin.viscat.com.au"
REGION = "ap-southeast-2"
USER_POOL_ID = os.environ["VISCAT_USER_POOL_ID"]  # e.g. ap-southeast-2_AbCdEfGhI
CLIENT_ID = os.environ["VISCAT_CLIENT_ID"]
USER_ID = os.environ["VISCAT_USER_ID"]  # from the SMS
SECRET = os.environ["VISCAT_SECRET"]  # from the SMS

REFRESH_MARGIN_SECONDS = 300  # refresh when less than 5 minutes remain


def jwt_expiry(token):
   """Return the token's exp claim (seconds since the epoch). No verification needed."""
   payload = token.split(".")[1]
   payload += "=" * (-len(payload) % 4)
   return json.loads(base64.urlsafe_b64decode(payload))["exp"]


class VisCatTokenManager:
   def __init__(self):
       # InitiateAuth needs no AWS credentials; boto3 sends it unsigned.
       self.cognito = boto3.client("cognito-idp", region_name=REGION)
       self.id_token = None
       self.refresh_token = None

   def login(self):
       """SRP login (USER_SRP_AUTH)."""
       srp = AWSSRP(
           username=USER_ID,
           password=SECRET,
           pool_id=USER_POOL_ID,
           client_id=CLIENT_ID,
           client=self.cognito,
       )
       result = srp.authenticate_user()["AuthenticationResult"]
       self.id_token = result["IdToken"]
       self.refresh_token = result["RefreshToken"]

   def refresh(self):
       """REFRESH_TOKEN_AUTH. Cognito returns no new refresh token."""
       result = self.cognito.initiate_auth(
           ClientId=CLIENT_ID,
           AuthFlow="REFRESH_TOKEN_AUTH",
           AuthParameters={"REFRESH_TOKEN": self.refresh_token},
       )["AuthenticationResult"]
       self.id_token = result["IdToken"]

   def get_id_token(self):
       if self.id_token is None:
           self.login()
       elif jwt_expiry(self.id_token) - time.time() < REFRESH_MARGIN_SECONDS:
           try:
               self.refresh()
           except self.cognito.exceptions.NotAuthorizedException:
               self.login()  # the 6-hour refresh token has expired
       return self.id_token

   def force_renew(self):
       """Call after a 401 to force a new login on the next get_id_token()."""
       self.id_token = None


def create_candidate(tokens, candidate):
   def send():
       return requests.post(
           f"{API_BASE_URL}/v2/partner/candidate",
           headers={"Authorization": f"Bearer {tokens.get_id_token()}"},
           json=candidate,
           timeout=30,
       )

   res = send()
   if res.status_code == 401:
       tokens.force_renew()  # retry once with a fresh token
       res = send()
   body = res.json()
   if res.status_code != 201:
       raise RuntimeError(f"VisCAT {res.status_code}: {body.get('message')}")
   return body  # {candidateId, test_url, customerId}


if __name__ == "__main__":
   tokens = VisCatTokenManager()
   created = create_candidate(
       tokens,
       {
           "firstName": "Joshua",
           "lastName": "El Khoury",
           "DoB": "2016-12-10",
           "reportContact": {"email": "parent@example.com", "name": "Jane El Khoury"},
           "customerId": "CUST-000123",
       },
   )
   print(f"Candidate {created['candidateId']}: {created['test_url']}")

Java

Uses the AWS SDK for Java 2.x for the Cognito calls and the JDK's HttpClient for the API. The SDK has no SRP helper, so CognitoSrp below does those steps. It follows the same algorithm as the AWS SDKs for JavaScript and Python. Copy it as is.

// Java 17+. Maven dependencies:
//   software.amazon.awssdk:cognitoidentityprovider  (AWS SDK for Java 2.x)
//   com.fasterxml.jackson.core:jackson-databind
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
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.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;

public class VisCatPartnerExample {
   static final String API_BASE_URL = "https://test.api.admin.viscat.com.au";
   static final ObjectMapper MAPPER = new ObjectMapper();
   static final HttpClient HTTP = HttpClient.newHttpClient();

   public static void main(String[] args) throws Exception {
       VisCatTokenManager tokens = new VisCatTokenManager(
           "ap-southeast-2",
           System.getenv("VISCAT_USER_POOL_ID"), // e.g. ap-southeast-2_AbCdEfGhI
           System.getenv("VISCAT_CLIENT_ID"),
           System.getenv("VISCAT_USER_ID"),      // from the SMS
           System.getenv("VISCAT_SECRET"));      // from the SMS

       JsonNode created = createCandidate(tokens, Map.of(
           "firstName", "Joshua",
           "lastName", "El Khoury",
           "DoB", "2016-12-10",
           "reportContact", Map.of("email", "parent@example.com", "name", "Jane El Khoury"),
           "customerId", "CUST-000123"));
       System.out.println("Candidate " + created.get("candidateId").asText()
           + ": " + created.get("test_url").asText());
   }

   static JsonNode createCandidate(VisCatTokenManager tokens, Map<String, Object> candidate) throws Exception {
       String body = MAPPER.writeValueAsString(candidate);
       HttpResponse<String> res = post(tokens.getIdToken(), body);
       if (res.statusCode() == 401) {
           tokens.forceRenew(); // retry once with a fresh token
           res = post(tokens.getIdToken(), body);
       }
       JsonNode json = MAPPER.readTree(res.body());
       if (res.statusCode() != 201) {
           throw new IllegalStateException("VisCAT " + res.statusCode() + ": " + json.path("message").asText());
       }
       return json; // {candidateId, test_url, customerId}
   }

   static HttpResponse<String> post(String idToken, String body) throws Exception {
       HttpRequest req = HttpRequest.newBuilder(URI.create(API_BASE_URL + "/v2/partner/candidate"))
           .header("Authorization", "Bearer " + idToken)
           .header("Content-Type", "application/json")
           .POST(HttpRequest.BodyPublishers.ofString(body))
           .build();
       return HTTP.send(req, HttpResponse.BodyHandlers.ofString());
   }
}

/** Logs in with SRP, refreshes the ID token before it expires, and logs in again when the refresh token expires. */
class VisCatTokenManager {
   private static final long REFRESH_MARGIN_SECONDS = 300; // refresh when less than 5 minutes remain

   private final CognitoIdentityProviderClient cognito;
   private final String userPoolId, clientId, userId, secret;
   private String idToken, refreshToken;

   VisCatTokenManager(String region, String userPoolId, String clientId, String userId, String secret) {
       // InitiateAuth and RespondToAuthChallenge need no AWS credentials.
       this.cognito = CognitoIdentityProviderClient.builder()
           .region(Region.of(region))
           .credentialsProvider(AnonymousCredentialsProvider.create())
           .build();
       this.userPoolId = userPoolId;
       this.clientId = clientId;
       this.userId = userId;
       this.secret = secret;
   }

   synchronized String getIdToken() throws Exception {
       if (idToken == null) {
           login();
       } else if (expiresAt(idToken) - Instant.now().getEpochSecond() < REFRESH_MARGIN_SECONDS) {
           try {
               refresh();
           } catch (NotAuthorizedException e) {
               login(); // the 6-hour refresh token has expired
           }
       }
       return idToken;
   }

   /** Call after a 401 to force a new login on the next getIdToken(). */
   synchronized void forceRenew() {
       idToken = null;
   }

   private void login() throws Exception {
       CognitoSrp srp = new CognitoSrp(userPoolId);
       InitiateAuthResponse init = cognito.initiateAuth(r -> r
           .authFlow(AuthFlowType.USER_SRP_AUTH)
           .clientId(clientId)
           .authParameters(Map.of("USERNAME", userId, "SRP_A", srp.srpA())));
       if (init.challengeName() != ChallengeNameType.PASSWORD_VERIFIER) {
           throw new IllegalStateException("Unexpected challenge: " + init.challengeNameAsString());
       }

       Map<String, String> answer = srp.passwordVerifier(init.challengeParameters(), secret);
       RespondToAuthChallengeResponse resp = cognito.respondToAuthChallenge(r -> r
           .clientId(clientId)
           .challengeName(ChallengeNameType.PASSWORD_VERIFIER)
           .challengeResponses(answer));
       AuthenticationResultType result = resp.authenticationResult();
       if (result == null) {
           throw new IllegalStateException("Unexpected challenge: " + resp.challengeNameAsString() + ". Contact VisCAT.");
       }
       idToken = result.idToken();
       refreshToken = result.refreshToken();
   }

   private void refresh() {
       AuthenticationResultType result = cognito.initiateAuth(r -> r
               .authFlow(AuthFlowType.REFRESH_TOKEN_AUTH)
               .clientId(clientId)
               .authParameters(Map.of("REFRESH_TOKEN", refreshToken)))
           .authenticationResult();
       idToken = result.idToken(); // Cognito returns no new refresh token
   }

   private static long expiresAt(String jwt) throws Exception {
       byte[] payload = Base64.getUrlDecoder().decode(jwt.split("\\.")[1]);
       return VisCatPartnerExample.MAPPER.readTree(payload).get("exp").asLong();
   }
}

/** Client side of Cognito's USER_SRP_AUTH, the same steps the AWS SDKs for JavaScript and Python run. */
class CognitoSrp {
   // RFC 3526 3072-bit prime, generator 2.
   private static final BigInteger N = new BigInteger(
       "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
     + "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
     + "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
     + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"
     + "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"
     + "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
     + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
     + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33"
     + "A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
     + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864"
     + "D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2"
     + "08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", 16);
   private static final BigInteger G = BigInteger.TWO;
   private static final BigInteger K = new BigInteger(1, sha256(N.toByteArray(), G.toByteArray()));
   private static final SecureRandom RANDOM = new SecureRandom();
   private static final DateTimeFormatter TIMESTAMP =
       DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss 'UTC' yyyy", Locale.US);

   private final String poolName; // the part of the pool ID after the underscore
   private final BigInteger a;
   private final BigInteger bigA;

   CognitoSrp(String userPoolId) {
       this.poolName = userPoolId.substring(userPoolId.indexOf('_') + 1);
       BigInteger smallA, largeA;
       do {
           smallA = new BigInteger(1024, RANDOM).mod(N);
           largeA = G.modPow(smallA, N);
       } while (largeA.signum() == 0);
       this.a = smallA;
       this.bigA = largeA;
   }

   String srpA() {
       return bigA.toString(16);
   }

   /** Answers the PASSWORD_VERIFIER challenge. */
   Map<String, String> passwordVerifier(Map<String, String> challenge, String password) throws Exception {
       String userIdForSrp = challenge.get("USER_ID_FOR_SRP");
       String secretBlock = challenge.get("SECRET_BLOCK");
       BigInteger bigB = new BigInteger(challenge.get("SRP_B"), 16);
       BigInteger salt = new BigInteger(challenge.get("SALT"), 16);
       if (bigB.mod(N).signum() == 0) throw new IllegalStateException("Invalid SRP_B from Cognito");

       // toByteArray() gives the same sign-padded bytes the AWS SDKs hash.
       BigInteger u = new BigInteger(1, sha256(bigA.toByteArray(), bigB.toByteArray()));
       if (u.signum() == 0) throw new IllegalStateException("Invalid SRP u value");
       byte[] userHash = sha256((poolName + userIdForSrp + ":" + password).getBytes(StandardCharsets.UTF_8));
       BigInteger x = new BigInteger(1, sha256(salt.toByteArray(), userHash));
       BigInteger s = bigB.subtract(K.multiply(G.modPow(x, N))).modPow(a.add(u.multiply(x)), N);

       // HKDF-SHA256: salt = u, input key = S, info = "Caldera Derived Key", 16-byte output.
       byte[] prk = hmac(u.toByteArray(), s.toByteArray());
       byte[] key = Arrays.copyOf(hmac(prk, "Caldera Derived Key\u0001".getBytes(StandardCharsets.UTF_8)), 16);

       String timestamp = ZonedDateTime.now(ZoneOffset.UTC).format(TIMESTAMP);
       ByteArrayOutputStream msg = new ByteArrayOutputStream();
       msg.writeBytes(poolName.getBytes(StandardCharsets.UTF_8));
       msg.writeBytes(userIdForSrp.getBytes(StandardCharsets.UTF_8));
       msg.writeBytes(Base64.getDecoder().decode(secretBlock));
       msg.writeBytes(timestamp.getBytes(StandardCharsets.UTF_8));
       String signature = Base64.getEncoder().encodeToString(hmac(key, msg.toByteArray()));

       return Map.of(
           "USERNAME", userIdForSrp,
           "PASSWORD_CLAIM_SECRET_BLOCK", secretBlock,
           "PASSWORD_CLAIM_SIGNATURE", signature,
           "TIMESTAMP", timestamp);
   }

   private static byte[] sha256(byte[]... parts) {
       try {
           MessageDigest md = MessageDigest.getInstance("SHA-256");
           for (byte[] part : parts) md.update(part);
           return md.digest();
       } catch (Exception e) {
           throw new IllegalStateException(e);
       }
   }

   private static byte[] hmac(byte[] key, byte[] data) throws Exception {
       Mac mac = Mac.getInstance("HmacSHA256");
       mac.init(new SecretKeySpec(key, "HmacSHA256"));
       return mac.doFinal(data);
   }
}

Troubleshooting and support

Most first-call failures come from one of these:

 

Request IDs. Every API response carries an X-Request-ID header. You may also send your own X-Request-ID and VisCAT will use it. Log it beside each call, and quote it when you contact support so we can find the request.


Contact. Send questions, rotation requests and incident reports to VisCAT partner support at <support contact to be confirmed>. Never include your secret in an email or ticket.


Copyright © 2026 Vis-CAT:  The Visual Cognition Assessment Tool - All Rights Reserved.

  • Privacy Policy
  • Terms and Conditions
  • Contact Us
  • Press Releases
  • FAQ
  • Vis-CAT Developer Guide

Powered by

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept