Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Clout Kit Web Services using server to server token
(function() {
/**
* This is an example fetching /users/current from cloud kit with a server to server token without utilising aplpe's cloudkit.js
* https://developer.apple.com/library/ios/samplecode/CloudAtlas/Listings/Node_node_client_s2s_index_js.html#//apple_ref/doc/uid/TP40014599-Node_node_client_s2s_index_js-DontLinkElementID_22
*/
const https = require('https');
var fs = require('fs');
var crypto = require('crypto');
// using config from cloud kit catalog example https://developer.apple.com/library/ios/samplecode/CloudAtlas/Listings/Node_node_client_s2s_config_js.html#//apple_ref/doc/uid/TP40014599-Node_node_client_s2s_config_js-DontLinkElementID_21
var containerConfig = require('./config');
var key = fs.readFileSync(containerConfig.serverToServerKeyAuth.privateKeyFile, "utf8");
// path of our request (domain not included)
var requestPath = "/database/1/" + containerConfig.containerIdentifier + "/development/public/users/current";
// request body (GET request is blank)
var requestBody = '';
// date string without miliseconds
var requestDate = (new Date).toISOString().replace(/(\.\d\d\d)Z/, "Z");
var bodyHasher = crypto.createHash('sha256');
bodyHasher.update(requestBody);
var hashedBody = bodyHasher.digest("base64");
var rawPayload = requestDate + ":" + hashedBody + ":" + requestPath;
// sign payload
var c = crypto.createSign("sha256");
c.update(rawPayload);
var requestSignature = c.sign(key, "base64");
// put headers together
var headers = {
'X-Apple-CloudKit-Request-KeyID': containerConfig.serverToServerKeyAuth.keyID,
'X-Apple-CloudKit-Request-ISO8601Date': requestDate,
'X-Apple-CloudKit-Request-SignatureV1': requestSignature
};
var options = {
hostname: 'api.apple-cloudkit.com',
port: 443,
path: requestPath,
method: 'GET',
headers: headers
};
var req = https.request(options, (res) => {
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.end();
req.on('error', (e) => {
console.error(e);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment