Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 0 additions & 49 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,56 +15,7 @@ The above copyright notice and this permission notice shall be included in all c

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.

_____________________

Brian J. Brennan (base64url)

Copyright (c) 2013–2016 Brian J. Brennan

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, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

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.

_____________________

Auth0, Inc. (jsonwebtoken)

The MIT License (MIT)

Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)

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, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.

_____________________

Expand Down
25 changes: 21 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ export { RenewalBillingPlanType } from './models/RenewalBillingPlanType'
export { RenewalCommitmentInfo } from './models/RenewalCommitmentInfo'
export { TransactionCommitmentInfo } from './models/TransactionCommitmentInfo'

import jsonwebtoken = require('jsonwebtoken');
import { sign } from 'crypto';
import { AppTransactionInfoResponse, AppTransactionInfoResponseValidator } from './models/AppTransactionInfoResponse';
import { NotificationHistoryRequest } from './models/NotificationHistoryRequest';
import { NotificationHistoryResponse, NotificationHistoryResponseValidator } from './models/NotificationHistoryResponse';
Expand Down Expand Up @@ -714,10 +714,27 @@ export class AppStoreServerAPIClient {
}

private createBearerToken(): string {
const now = Math.floor(Date.now() / 1000);
const payload = {
bid: this.bundleId
}
return jsonwebtoken.sign(payload, this.signingKey, { algorithm: 'ES256', keyid: this.keyId, issuer: this.issuerId, audience: 'appstoreconnect-v1', expiresIn: '5m'});
bid: this.bundleId,
iss: this.issuerId,
aud: 'appstoreconnect-v1',
iat: now,
exp: now + 300
};
const header = {
alg: 'ES256',
kid: this.keyId,
typ: 'JWT'
};
const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64url');
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signingInput = `${headerB64}.${payloadB64}`;
const signature = sign('SHA256', Buffer.from(signingInput), {
key: this.signingKey,
dsaEncoding: 'ieee-p1363'
}).toString('base64url');
return `${signingInput}.${signature}`;
}
}

Expand Down
24 changes: 19 additions & 5 deletions jws_signature_creator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) 2025 Apple Inc. Licensed under MIT License.

import jsonwebtoken = require('jsonwebtoken');
import { randomUUID } from 'crypto';
import { randomUUID, sign } from 'crypto';

class BaseSignatureCreator {
private audience: string
Expand All @@ -18,13 +17,28 @@ class BaseSignatureCreator {
this.signingKey = signingKey
}

protected internalCreateSignature(featureSpecificClaims: { [key: string]: any }) {
var claims = featureSpecificClaims
protected internalCreateSignature(featureSpecificClaims: { [key: string]: any }): string {
const claims = { ...featureSpecificClaims }

claims['bid'] = this.bundleId
claims['nonce'] = randomUUID()
claims['iss'] = this.issuerId
claims['aud'] = this.audience
claims['iat'] = Math.floor(Date.now() / 1000)

return jsonwebtoken.sign(claims, this.signingKey, { algorithm: 'ES256', keyid: this.keyId, issuer: this.issuerId, audience: this.audience})
const header = {
alg: 'ES256',
kid: this.keyId,
typ: 'JWT'
}
const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64url')
const payloadB64 = Buffer.from(JSON.stringify(claims)).toString('base64url')
const signingInput = `${headerB64}.${payloadB64}`
const signature = sign('SHA256', Buffer.from(signingInput), {
key: this.signingKey,
dsaEncoding: 'ieee-p1363'
}).toString('base64url')
return `${signingInput}.${signature}`
}
}

Expand Down
28 changes: 17 additions & 11 deletions jws_verification.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
// Copyright (c) 2023 Apple Inc. Licensed under MIT License.

import jsonwebtoken = require('jsonwebtoken');

import base64url from 'base64url';
import { KeyObject, X509Certificate, createHash, verify } from 'crypto';
import { KJUR, X509, ASN1HEX } from 'jsrsasign';
import fetch, { Headers } from 'node-fetch';
Expand Down Expand Up @@ -205,7 +202,12 @@ export class SignedDataVerifier {
let certificateChain;
let decodedJWT
try {
decodedJWT = jsonwebtoken.decode(jwt)
const parts = jwt.split('.')
if (parts.length !== 3) {
throw new Error("Invalid JWT format")
}
const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8')
decodedJWT = JSON.parse(payloadJson)
if (!validator.validate(decodedJWT)) {
throw new VerificationException(VerificationStatus.FAILURE)
}
Expand All @@ -215,8 +217,8 @@ export class SignedDataVerifier {
return decodedJWT
}
try {
const header = jwt.split('.')[0]
const decodedHeader = base64url.decode(header)
const header = parts[0]
const decodedHeader = Buffer.from(header, 'base64url').toString('utf8')
const headerObj = JSON.parse(decodedHeader)
const chain: string[] = headerObj['x5c'] ?? []
if (chain.length != 3) {
Expand All @@ -231,11 +233,15 @@ export class SignedDataVerifier {
}
const effectiveDate = this.enableOnlineChecks ? new Date() : signedDateExtractor(decodedJWT)
const publicKey = await this.verifyCertificateChain(this.rootCertificates, certificateChain[0], certificateChain[1], effectiveDate);
const encodedKey = publicKey.export({
type: "spki",
format: "pem"
});
jsonwebtoken.verify(jwt, encodedKey) as T
const signingInput = Buffer.from(`${parts[0]}.${parts[1]}`)
const signature = Buffer.from(parts[2], 'base64url')
const isSignatureValid = verify('SHA256', signingInput, {
key: publicKey,
dsaEncoding: 'ieee-p1363'
}, signature)
if (!isSignatureValid) {
throw new VerificationException(VerificationStatus.VERIFICATION_FAILURE)
}
return decodedJWT
} catch (error) {
if (error instanceof VerificationException) {
Expand Down
3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@
},
"types": "dist/index.d.ts",
"dependencies": {
"@types/jsonwebtoken": "^9.0.5",
"@types/jsrsasign": "^10.5.12",
"@types/node": "^26.3.0",
"@types/node-fetch": "^2.6.13",
"base64url": "^3.0.1",
"jsonwebtoken": "^9.0.2",
"jsrsasign": "^11.1.5",
"node-fetch": "^2.7.0"
},
Expand Down
5 changes: 2 additions & 3 deletions tests/unit-tests/api_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ import { RefundPreferenceV1 } from "../../models/RefundPreferenceV1";
import { APIError, APIException, AppStoreServerAPIClient, ExtendReasonCode, ExtendRenewalDateRequest, GetTransactionHistoryVersion, MassExtendRenewalDateRequest, NotificationHistoryRequest, NotificationHistoryResponseItem, Order, OrderLookupStatus, ProductType, SendAttemptResult, TransactionHistoryRequest } from "../../index";
import { Response } from "node-fetch";

import jsonwebtoken = require('jsonwebtoken');

type callbackType = (path: string, parsedQueryParameters: URLSearchParams, method: string, requestBody: string | Buffer | undefined, headers: { [key: string]: string; }) => void

class AppStoreServerAPIClientForTest extends AppStoreServerAPIClient {
Expand Down Expand Up @@ -55,7 +53,8 @@ class AppStoreServerAPIClientForTest extends AppStoreServerAPIClient {
expect('application/json').toBe(headers['Accept'])
expect(headers['Authorization']).toMatch(/^Bearer .+/)
const token = headers['Authorization'].substring(7)
const decodedToken = jsonwebtoken.decode(token) as jsonwebtoken.JwtPayload
const parts = token.split('.')
const decodedToken = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))
expect(decodedToken['bid']).toBe('bundleId')
expect(decodedToken['aud']).toBe('appstoreconnect-v1')
expect(decodedToken['iss']).toBe('issuerId')
Expand Down
1 change: 0 additions & 1 deletion tests/unit-tests/jws_signature_creator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import { AdvancedCommerceInAppRequest, AdvancedCommerceInAppSignatureCreator, IntroductoryOfferEligibilitySignatureCreator, PromotionalOfferV2SignatureCreator } from "../../jws_signature_creator";
import { readFile } from "../util"
import jsonwebtoken = require('jsonwebtoken');

interface TestInAppRequest extends AdvancedCommerceInAppRequest {
testValue: string
Expand Down
13 changes: 10 additions & 3 deletions tests/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import * as fs from 'fs';
import { Environment } from '../models/Environment';
import { SignedDataVerifier } from '../jws_verification';
import { ECKeyPairOptions, generateKeyPairSync } from 'crypto';
import jsonwebtoken = require('jsonwebtoken');
import { ECKeyPairOptions, generateKeyPairSync, sign } from 'crypto';

export function readFile(path: string): string {
return fs.readFileSync(path, {
Expand Down Expand Up @@ -44,5 +43,13 @@ export function createSignedDataFromJson(path: string): string {
const keypair = generateKeyPairSync("ec", keyPairOptions)
// When PEM encoding was selected, the respective key will be a string, otherwise it will be a buffer containing the data encoded as DER.
const privateKey = keypair.privateKey as string
return jsonwebtoken.sign(fileContents, privateKey, { algorithm: 'ES256'});
const header = { alg: 'ES256', typ: 'JWT' }
const headerB64 = Buffer.from(JSON.stringify(header)).toString('base64url')
const payloadB64 = Buffer.from(fileContents).toString('base64url')
const signingInput = `${headerB64}.${payloadB64}`
const signature = sign('SHA256', Buffer.from(signingInput), {
key: privateKey,
dsaEncoding: 'ieee-p1363'
}).toString('base64url')
return `${signingInput}.${signature}`
}
Loading