fruit-company
Version:
Apple services library
108 lines • 4.83 kB
JavaScript
;
/*
* MIT No Attribution
*
* Copyright 2024 Peter "Kevin" Contreras
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapsToken = void 0;
const date_fns_1 = require("date-fns");
const jose_1 = require("jose");
const serene_front_1 = require("serene-front");
const urls_1 = require("serene-front/urls");
const models_1 = require("./models");
/**
* A token used to interact with weather services.
*/
class MapsToken {
/**
* Create a token to interact with weather services.
*
* @param appId An app identifier from an Apple developer account.
* @param teamId A team identifier from an Apple developer account.
* @param keyId The identifier of the key used to sign requests.
* @param privateKey A WeatherKit REST key generated using an Apple developer account.
*/
constructor(appId, teamId, keyId, privateKey) {
this.appId = appId;
this.teamId = teamId;
this.keyId = keyId;
this.privateKey = privateKey;
this.accessToken = "";
this.expiresAt = new Date(0);
}
get retryLimit() {
return 2;
}
get isValid() {
return (this.accessToken !== "" && this.expiresAt >= new Date());
}
refresh(_a) {
return __awaiter(this, arguments, void 0, function* ({ fetch }) {
const privateKeyPKCS8 = yield (0, jose_1.importPKCS8)(this.privateKey, "ES256");
const signBearerTokenPayload = new jose_1.SignJWT({ sub: this.appId })
.setIssuer(this.teamId)
.setIssuedAt()
.setExpirationTime("1 m")
.setProtectedHeader({
alg: "ES256",
kid: this.keyId,
typ: "JWT",
id: `${this.teamId}.${this.appId}`,
});
const authToken = yield signBearerTokenPayload.sign(privateKeyPKCS8);
const response = yield fetch(`${models_1.mapKitApiUrl}/token`, {
headers: {
Authorization: `Bearer ${authToken}`,
},
});
if (!response.ok) {
const errorResponse = yield response.json();
throw new serene_front_1.AuthorityError(response.status, response.statusText, `${errorResponse.message} (${errorResponse.details.join(', ')})`);
}
const tokenResponse = yield response.json();
this.accessToken = tokenResponse.accessToken;
this.expiresAt = (0, date_fns_1.addSeconds)(new Date(), tokenResponse.expiresInSeconds);
});
}
authenticate(_a) {
return __awaiter(this, arguments, void 0, function* ({ fetchRequest }) {
if (!this.isValid) {
throw new serene_front_1.AuthorityError(401, "Unauthorized", "Invalid MapsToken cannot be used to authenticate requests.");
}
return (0, urls_1.setRequestHeaders)(fetchRequest, [
["Authorization", `Bearer ${this.accessToken}`],
]);
});
}
/**
* @ignore
*/
toString() {
return `MapsToken(isValid: ${this.isValid}, expiresAt: ${this.expiresAt})`;
}
}
exports.MapsToken = MapsToken;
//# sourceMappingURL=token.js.map