@base44-preview/sdk 0.8.48-pr.276.4f760f9 → 0.8.48-pr.276.5321860
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/iap/config.d.ts +1 -0
- package/dist/iap/config.js +7 -1
- package/dist/iap/iap.types.d.ts +14 -0
- package/dist/iap/index.js +9 -4
- package/dist/iap/verify/apple-verifier.d.ts +13 -0
- package/dist/iap/verify/apple-verifier.js +154 -0
- package/dist/iap/verify/asn1.d.ts +102 -0
- package/dist/iap/verify/asn1.js +247 -0
- package/dist/iap/verify/chain.d.ts +40 -0
- package/dist/iap/verify/chain.js +112 -0
- package/dist/iap/verify/ecdsa.d.ts +16 -0
- package/dist/iap/verify/ecdsa.js +86 -0
- package/dist/iap/verify/jws.d.ts +50 -0
- package/dist/iap/verify/jws.js +159 -0
- package/dist/iap/verify/payload-checks.d.ts +22 -16
- package/dist/iap/verify/payload-checks.js +59 -3
- package/dist/iap/verify/verifier.d.ts +15 -21
- package/dist/iap/verify/verifier.js +82 -129
- package/dist/iap/verify/x509.d.ts +83 -0
- package/dist/iap/verify/x509.js +156 -0
- package/package.json +1 -1
package/dist/iap/config.d.ts
CHANGED
package/dist/iap/config.js
CHANGED
|
@@ -25,7 +25,7 @@ function invalid(message) {
|
|
|
25
25
|
* `IAP_ONLINE_CHECKS_UNSUPPORTED` when online certificate checks are asked for.
|
|
26
26
|
*/
|
|
27
27
|
export function resolveConfig(config) {
|
|
28
|
-
var _a;
|
|
28
|
+
var _a, _b;
|
|
29
29
|
if (!config || typeof config !== "object") {
|
|
30
30
|
invalid("an in-app purchase configuration object is required");
|
|
31
31
|
}
|
|
@@ -67,6 +67,11 @@ export function resolveConfig(config) {
|
|
|
67
67
|
// `null` is treated as absent, not as invalid: a secret that was never set
|
|
68
68
|
// arrives that way, and the right answer then is "the API is not configured"
|
|
69
69
|
// — which the call itself reports clearly — rather than refusing to start.
|
|
70
|
+
if (config.verifier !== undefined &&
|
|
71
|
+
config.verifier !== "apple" &&
|
|
72
|
+
config.verifier !== "builtin") {
|
|
73
|
+
invalid(`'verifier' must be "apple" or "builtin"; got ${JSON.stringify(config.verifier)}`);
|
|
74
|
+
}
|
|
70
75
|
if (config.serverApi !== undefined && config.serverApi !== null) {
|
|
71
76
|
const api = config.serverApi;
|
|
72
77
|
if (typeof api !== "object") {
|
|
@@ -95,5 +100,6 @@ export function resolveConfig(config) {
|
|
|
95
100
|
testMode: config.testMode === true,
|
|
96
101
|
allowLocalTesting: config.allowLocalTesting === true,
|
|
97
102
|
serverApi: (_a = config.serverApi) !== null && _a !== void 0 ? _a : undefined,
|
|
103
|
+
verifier: (_b = config.verifier) !== null && _b !== void 0 ? _b : "apple",
|
|
98
104
|
};
|
|
99
105
|
}
|
package/dist/iap/iap.types.d.ts
CHANGED
|
@@ -131,6 +131,20 @@ export interface IapConfig {
|
|
|
131
131
|
* in Base44 secrets.
|
|
132
132
|
*/
|
|
133
133
|
serverApi?: IapServerApiConfig;
|
|
134
|
+
/**
|
|
135
|
+
* Which implementation verifies Apple's signed tokens.
|
|
136
|
+
*
|
|
137
|
+
* `"apple"` (the default) uses Apple's own `app-store-server-library`.
|
|
138
|
+
* `"builtin"` uses this SDK's own verifier, which needs no Node built-ins
|
|
139
|
+
* and runs anywhere WebCrypto does.
|
|
140
|
+
*
|
|
141
|
+
* Both enforce the same rules and produce the same decoded payloads, so this
|
|
142
|
+
* can be flipped without touching any other code. Switch to `"builtin"` if
|
|
143
|
+
* Apple's library turns out not to survive the Cloudflare Workers bundler.
|
|
144
|
+
*
|
|
145
|
+
* @defaultValue `"apple"`
|
|
146
|
+
*/
|
|
147
|
+
verifier?: "apple" | "builtin";
|
|
134
148
|
/**
|
|
135
149
|
* Whether to ask Apple's servers whether a certificate has been revoked.
|
|
136
150
|
*
|
package/dist/iap/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { appAccountTokenFor } from "./account-token.js";
|
|
2
2
|
import { resolveConfig } from "./config.js";
|
|
3
3
|
import { createVerifier } from "./verify/verifier.js";
|
|
4
|
+
import { createAppleVerifier } from "./verify/apple-verifier.js";
|
|
4
5
|
import { systemClock } from "./runtime/clock.js";
|
|
5
6
|
import { createEmitter } from "./events/emitter.js";
|
|
6
7
|
import { createEntitiesStore } from "./store/entities-store.js";
|
|
@@ -58,18 +59,22 @@ import { recordTransaction, syncEntitlements } from "./ingest/device.js";
|
|
|
58
59
|
* ```
|
|
59
60
|
*/
|
|
60
61
|
export function createIapClient(options) {
|
|
61
|
-
var _a, _b, _c, _d, _e;
|
|
62
|
+
var _a, _b, _c, _d, _e, _f;
|
|
62
63
|
if (!options || !options.base44) {
|
|
63
64
|
throw new TypeError("createIapClient needs a Base44 client — create one with createClientFromRequest(request)");
|
|
64
65
|
}
|
|
65
66
|
const config = resolveConfig(options.config);
|
|
66
67
|
const clock = (_b = (_a = options.internal) === null || _a === void 0 ? void 0 : _a.clock) !== null && _b !== void 0 ? _b : systemClock;
|
|
67
|
-
|
|
68
|
+
// Both implementations satisfy the same interface, so nothing downstream
|
|
69
|
+
// knows or cares which one ran.
|
|
70
|
+
const verifier = config.verifier === "apple"
|
|
71
|
+
? createAppleVerifier({ config, roots: (_c = options.internal) === null || _c === void 0 ? void 0 : _c.roots })
|
|
72
|
+
: createVerifier({ config, roots: (_d = options.internal) === null || _d === void 0 ? void 0 : _d.roots, clock });
|
|
68
73
|
const store = createEntitiesStore({
|
|
69
74
|
// Reached lazily: the service-role accessor throws when the client has no
|
|
70
75
|
// service credentials, and constructing an IAP client must not.
|
|
71
76
|
getEntities: () => options.base44.asServiceRole.entities,
|
|
72
|
-
mode: (
|
|
77
|
+
mode: (_e = options.internal) === null || _e === void 0 ? void 0 : _e.storeMode,
|
|
73
78
|
clock,
|
|
74
79
|
});
|
|
75
80
|
const emitter = createEmitter();
|
|
@@ -99,7 +104,7 @@ export function createIapClient(options) {
|
|
|
99
104
|
// A sandbox app's transactions live in the sandbox environment, so try
|
|
100
105
|
// it first there and save a round trip.
|
|
101
106
|
preferSandbox: config.testMode,
|
|
102
|
-
fetchImpl: (
|
|
107
|
+
fetchImpl: (_f = options.internal) === null || _f === void 0 ? void 0 : _f.fetchImpl,
|
|
103
108
|
}),
|
|
104
109
|
hasActiveSubscription: reader.hasActiveSubscription,
|
|
105
110
|
getSubscriptionState: reader.getSubscriptionState,
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PayloadCheckConfig } from "./payload-checks.js";
|
|
2
|
+
import type { Verifier } from "./verifier.js";
|
|
3
|
+
/** Inputs to {@link createAppleVerifier}. */
|
|
4
|
+
export interface CreateAppleVerifierOptions {
|
|
5
|
+
readonly config: PayloadCheckConfig;
|
|
6
|
+
/** Trust anchors, for this SDK's own tests. Defaults to Apple's pinned roots. @internal */
|
|
7
|
+
readonly roots?: readonly {
|
|
8
|
+
readonly der: Uint8Array;
|
|
9
|
+
}[];
|
|
10
|
+
/** Whether to do OCSP revocation lookups. Off unless explicitly enabled. */
|
|
11
|
+
readonly onlineChecks?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare function createAppleVerifier(options: CreateAppleVerifierOptions): Verifier;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The same verification surface, backed by Apple's own library.
|
|
3
|
+
*
|
|
4
|
+
* An alternative to the built-in verifier, selected with `verifier: "apple"`.
|
|
5
|
+
* It exists because Apple's library is authoritative and does two things the
|
|
6
|
+
* built-in one does not — it checks the intermediate's CA basic constraint,
|
|
7
|
+
* and it can do OCSP revocation lookups.
|
|
8
|
+
*
|
|
9
|
+
* Two structural differences drive the code below.
|
|
10
|
+
*
|
|
11
|
+
* **One environment per instance.** `SignedDataVerifier` is constructed for a
|
|
12
|
+
* single `Environment` and rejects payloads from any other, so accepting both
|
|
13
|
+
* production and sandbox means holding one instance per environment and trying
|
|
14
|
+
* each in turn.
|
|
15
|
+
*
|
|
16
|
+
* **It reaches for Node built-ins.** `node:crypto`, `Buffer` and `node-fetch`.
|
|
17
|
+
* Base44 backend functions run on Cloudflare Workers with `nodejs_compat`,
|
|
18
|
+
* which does provide `X509Certificate` — but this path is unproven there,
|
|
19
|
+
* which is exactly why the built-in verifier is kept and reachable by config.
|
|
20
|
+
*
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
import { Environment, SignedDataVerifier, VerificationStatus, } from "@apple/app-store-server-library";
|
|
24
|
+
import { base64UrlToBytes } from "../runtime/base64.js";
|
|
25
|
+
import { IapVerificationError } from "../errors.js";
|
|
26
|
+
import { appleRoots } from "./apple-roots.js";
|
|
27
|
+
/** Apple's failure codes, mapped onto this SDK's. */
|
|
28
|
+
const STATUS_TO_CODE = {
|
|
29
|
+
[VerificationStatus.INVALID_APP_IDENTIFIER]: "INVALID_APP_IDENTIFIER",
|
|
30
|
+
[VerificationStatus.INVALID_ENVIRONMENT]: "INVALID_ENVIRONMENT",
|
|
31
|
+
[VerificationStatus.INVALID_CHAIN_LENGTH]: "INVALID_CHAIN_LENGTH",
|
|
32
|
+
[VerificationStatus.INVALID_CERTIFICATE]: "INVALID_CERTIFICATE",
|
|
33
|
+
[VerificationStatus.VERIFICATION_FAILURE]: "INVALID_SIGNATURE",
|
|
34
|
+
[VerificationStatus.RETRYABLE_VERIFICATION_FAILURE]: "RETRYABLE_VERIFICATION_FAILURE",
|
|
35
|
+
[VerificationStatus.FAILURE]: "INVALID_JWS_FORMAT",
|
|
36
|
+
};
|
|
37
|
+
function toIapError(error) {
|
|
38
|
+
const status = error === null || error === void 0 ? void 0 : error.status;
|
|
39
|
+
const code = status !== undefined ? STATUS_TO_CODE[status] : undefined;
|
|
40
|
+
return new IapVerificationError(code !== null && code !== void 0 ? code : "INVALID_SIGNATURE", error instanceof Error ? error.message : String(error), { cause: error });
|
|
41
|
+
}
|
|
42
|
+
export function createAppleVerifier(options) {
|
|
43
|
+
var _a;
|
|
44
|
+
const { config } = options;
|
|
45
|
+
// Apple's library takes Node Buffers. On Cloudflare Workers these come from
|
|
46
|
+
// `nodejs_compat`; in tests, from Node itself.
|
|
47
|
+
const rootBuffers = ((_a = options.roots) !== null && _a !== void 0 ? _a : appleRoots()).map((root) => Buffer.from(root.der));
|
|
48
|
+
/**
|
|
49
|
+
* One verifier per accepted environment, most likely first.
|
|
50
|
+
*
|
|
51
|
+
* Production is always accepted. Sandbox needs `testMode`. Xcode is absent
|
|
52
|
+
* on purpose: Apple's library skips signature checks entirely for it, and
|
|
53
|
+
* routing to it would mean trusting an unverified `environment` claim to
|
|
54
|
+
* decide whether to verify at all.
|
|
55
|
+
*/
|
|
56
|
+
const verifiers = new Map();
|
|
57
|
+
const environments = [Environment.PRODUCTION];
|
|
58
|
+
if (config.testMode)
|
|
59
|
+
environments.push(Environment.SANDBOX);
|
|
60
|
+
for (const environment of environments) {
|
|
61
|
+
verifiers.set(environment, new SignedDataVerifier(rootBuffers, options.onlineChecks === true, environment, config.bundleId,
|
|
62
|
+
// Apple's verifier requires this in production and rejects it in
|
|
63
|
+
// sandbox, where its own payloads never carry one.
|
|
64
|
+
environment === Environment.PRODUCTION ? config.appAppleId : undefined));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reads the `environment` a token declares, without verifying anything.
|
|
68
|
+
*
|
|
69
|
+
* Only ever used to pick which verifier to hand the token to. It cannot be
|
|
70
|
+
* used to bypass a check: the chosen verifier re-reads the same field and
|
|
71
|
+
* rejects a mismatch, so a forged value just routes the token to an instance
|
|
72
|
+
* that refuses it.
|
|
73
|
+
*
|
|
74
|
+
* Routing beats trying each instance in turn, because Apple's library checks
|
|
75
|
+
* the app identifier *before* the environment — so a sandbox payload offered
|
|
76
|
+
* to the production instance fails as `INVALID_APP_IDENTIFIER`, which is
|
|
77
|
+
* indistinguishable from a token genuinely meant for another app.
|
|
78
|
+
*/
|
|
79
|
+
function declaredEnvironment(token) {
|
|
80
|
+
try {
|
|
81
|
+
const segment = token.split(".")[1];
|
|
82
|
+
if (!segment)
|
|
83
|
+
return undefined;
|
|
84
|
+
const payload = JSON.parse(new TextDecoder().decode(base64UrlToBytes(segment)));
|
|
85
|
+
const direct = payload.environment;
|
|
86
|
+
if (typeof direct === "string")
|
|
87
|
+
return direct;
|
|
88
|
+
// A notification carries it inside whichever block it has.
|
|
89
|
+
for (const key of ["data", "summary", "appData"]) {
|
|
90
|
+
const block = payload[key];
|
|
91
|
+
if (block && typeof block.environment === "string") {
|
|
92
|
+
return block.environment;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch (_a) {
|
|
97
|
+
// Malformed input: let the real verifier produce the error.
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
/** Hands the token to the verifier for the environment it declares. */
|
|
102
|
+
async function withVerifier(token, attempt) {
|
|
103
|
+
var _a;
|
|
104
|
+
const declared = declaredEnvironment(token);
|
|
105
|
+
const verifier = (_a = (declared !== undefined ? verifiers.get(declared) : undefined)) !== null && _a !== void 0 ? _a : verifiers.get(Environment.PRODUCTION);
|
|
106
|
+
if (declared !== undefined && !verifiers.has(declared)) {
|
|
107
|
+
throw new IapVerificationError("INVALID_ENVIRONMENT", `this token is from the ${declared} environment, which this app does not ` +
|
|
108
|
+
"accept (set testMode to accept Sandbox)");
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return await attempt(verifier);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw toIapError(error);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function verifyTransaction(jws) {
|
|
118
|
+
return withVerifier(jws, async (verifier) => (await verifier.verifyAndDecodeTransaction(jws)));
|
|
119
|
+
}
|
|
120
|
+
async function verifyRenewalInfo(jws) {
|
|
121
|
+
return withVerifier(jws, async (verifier) => (await verifier.verifyAndDecodeRenewalInfo(jws)));
|
|
122
|
+
}
|
|
123
|
+
async function verifyNotification(signedPayload) {
|
|
124
|
+
const decoded = await withVerifier(signedPayload, async (verifier) => verifier.verifyAndDecodeNotification(signedPayload));
|
|
125
|
+
const raw = decoded;
|
|
126
|
+
const rawData = raw.data;
|
|
127
|
+
let data;
|
|
128
|
+
if (rawData) {
|
|
129
|
+
const { signedTransactionInfo, signedRenewalInfo, ...rest } = rawData;
|
|
130
|
+
data = { ...rest };
|
|
131
|
+
// The inner tokens are verified separately, and the raw strings are
|
|
132
|
+
// replaced by their decoded form under names that say so — matching the
|
|
133
|
+
// built-in verifier, so the ingestion layer cannot tell the two apart.
|
|
134
|
+
if (typeof signedTransactionInfo === "string") {
|
|
135
|
+
data.transactionInfo = await verifyTransaction(signedTransactionInfo);
|
|
136
|
+
data.transactionInfoJws = signedTransactionInfo;
|
|
137
|
+
}
|
|
138
|
+
if (typeof signedRenewalInfo === "string") {
|
|
139
|
+
data.renewalInfo = await verifyRenewalInfo(signedRenewalInfo);
|
|
140
|
+
data.renewalInfoJws = signedRenewalInfo;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const notificationUUID = raw.notificationUUID;
|
|
144
|
+
const notificationType = raw.notificationType;
|
|
145
|
+
if (typeof notificationUUID !== "string" || notificationUUID.length === 0) {
|
|
146
|
+
throw new IapVerificationError("INVALID_JWS_FORMAT", "the notification carries no 'notificationUUID', so it cannot be de-duplicated");
|
|
147
|
+
}
|
|
148
|
+
if (typeof notificationType !== "string" || notificationType.length === 0) {
|
|
149
|
+
throw new IapVerificationError("INVALID_JWS_FORMAT", "the notification carries no 'notificationType'");
|
|
150
|
+
}
|
|
151
|
+
return { ...raw, notificationUUID, notificationType, data };
|
|
152
|
+
}
|
|
153
|
+
return { verifyTransaction, verifyRenewalInfo, verifyNotification };
|
|
154
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal DER reader, enough to walk an X.509 certificate.
|
|
3
|
+
*
|
|
4
|
+
* Scope on purpose: this reads the handful of fields certificate-chain
|
|
5
|
+
* validation needs and nothing else. It is a *reader* only — nothing here
|
|
6
|
+
* encodes. It is strict where laxness would be a security hole:
|
|
7
|
+
*
|
|
8
|
+
* - Definite-length form only. Indefinite length (BER, `0x80`) is rejected.
|
|
9
|
+
* - A length that runs past the end of the buffer is rejected, never clamped.
|
|
10
|
+
* - Every accessor is bounds-checked and throws rather than returning a
|
|
11
|
+
* partial value.
|
|
12
|
+
*
|
|
13
|
+
* The one thing callers must be able to get at is the *raw* bytes of a node
|
|
14
|
+
* including its header, because a certificate signature covers the encoded
|
|
15
|
+
* `tbsCertificate`, not a re-encoding of its contents.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
/** DER tag numbers this module recognises. */
|
|
20
|
+
export declare const Tag: {
|
|
21
|
+
readonly INTEGER: 2;
|
|
22
|
+
readonly BIT_STRING: 3;
|
|
23
|
+
readonly OCTET_STRING: 4;
|
|
24
|
+
readonly NULL: 5;
|
|
25
|
+
readonly OBJECT_IDENTIFIER: 6;
|
|
26
|
+
readonly UTF8_STRING: 12;
|
|
27
|
+
readonly SEQUENCE: 48;
|
|
28
|
+
readonly SET: 49;
|
|
29
|
+
readonly UTC_TIME: 23;
|
|
30
|
+
readonly GENERALIZED_TIME: 24;
|
|
31
|
+
readonly BOOLEAN: 1;
|
|
32
|
+
};
|
|
33
|
+
/** Thrown for input that is not well-formed DER. */
|
|
34
|
+
export declare class DerError extends Error {
|
|
35
|
+
constructor(message: string);
|
|
36
|
+
}
|
|
37
|
+
/** One parsed tag-length-value triple, described by offsets into the source buffer. */
|
|
38
|
+
export interface DerNode {
|
|
39
|
+
/** The tag byte. */
|
|
40
|
+
readonly tag: number;
|
|
41
|
+
/** Offset of the tag byte. */
|
|
42
|
+
readonly start: number;
|
|
43
|
+
/** Offset of the first content byte. */
|
|
44
|
+
readonly contentStart: number;
|
|
45
|
+
/** Content length in bytes. */
|
|
46
|
+
readonly length: number;
|
|
47
|
+
/** Offset one past the final content byte, i.e. the start of the next node. */
|
|
48
|
+
readonly end: number;
|
|
49
|
+
}
|
|
50
|
+
/** Reads one node at `offset`. */
|
|
51
|
+
export declare function readNode(buf: Uint8Array, offset: number): DerNode;
|
|
52
|
+
/** Reads one node at `offset` and asserts its tag. */
|
|
53
|
+
export declare function readNodeOfTag(buf: Uint8Array, offset: number, tag: number, what: string): DerNode;
|
|
54
|
+
/** The node's content bytes, without its header. A view, not a copy. */
|
|
55
|
+
export declare function content(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
56
|
+
/**
|
|
57
|
+
* The node's complete encoding, header included.
|
|
58
|
+
*
|
|
59
|
+
* This is what a signature covers. Re-encoding the parsed contents instead
|
|
60
|
+
* would be a bug: DER has canonical forms, but a signer's bytes are the only
|
|
61
|
+
* bytes that verify.
|
|
62
|
+
*/
|
|
63
|
+
export declare function raw(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
64
|
+
/** Every immediate child of a constructed node, in order. */
|
|
65
|
+
export declare function children(buf: Uint8Array, node: DerNode): DerNode[];
|
|
66
|
+
/** The child at `index`, or `undefined` when the node has fewer children. */
|
|
67
|
+
export declare function childAt(buf: Uint8Array, node: DerNode, index: number): DerNode | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* Decodes an OBJECT IDENTIFIER to dotted-decimal form.
|
|
70
|
+
*
|
|
71
|
+
* The first byte packs two arcs: `40 * first + second`, with the first arc
|
|
72
|
+
* capped at 2. Every later arc is base-128 with the high bit as a
|
|
73
|
+
* continuation flag.
|
|
74
|
+
*/
|
|
75
|
+
export declare function readOid(buf: Uint8Array, node: DerNode): string;
|
|
76
|
+
/**
|
|
77
|
+
* Decodes a BIT STRING's payload, dropping the unused-bits count byte.
|
|
78
|
+
*
|
|
79
|
+
* Every BIT STRING this module reads — a SubjectPublicKey, a certificate
|
|
80
|
+
* signature — is byte-aligned, so a non-zero unused-bits count means the
|
|
81
|
+
* parse has gone wrong and is rejected rather than shifted.
|
|
82
|
+
*/
|
|
83
|
+
export declare function readBitString(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
84
|
+
/**
|
|
85
|
+
* Decodes an INTEGER's magnitude with any DER sign padding removed.
|
|
86
|
+
*
|
|
87
|
+
* DER prepends a zero byte when the high bit would otherwise read as
|
|
88
|
+
* negative. ECDSA `r` and `s` are unsigned, so that byte must go before the
|
|
89
|
+
* value is padded to its fixed width.
|
|
90
|
+
*/
|
|
91
|
+
export declare function readUnsignedInteger(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
92
|
+
/**
|
|
93
|
+
* Decodes a UTCTime or GeneralizedTime to epoch milliseconds.
|
|
94
|
+
*
|
|
95
|
+
* Only the UTC (`Z`) form is accepted. Certificates may legally carry a
|
|
96
|
+
* numeric offset, but Apple's do not, and accepting one would mean
|
|
97
|
+
* hand-rolling timezone arithmetic for no gain.
|
|
98
|
+
*
|
|
99
|
+
* Per RFC 5280, a two-digit UTCTime year of 50 or more means 19xx, and less
|
|
100
|
+
* than 50 means 20xx.
|
|
101
|
+
*/
|
|
102
|
+
export declare function readTime(buf: Uint8Array, node: DerNode): number;
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal DER reader, enough to walk an X.509 certificate.
|
|
3
|
+
*
|
|
4
|
+
* Scope on purpose: this reads the handful of fields certificate-chain
|
|
5
|
+
* validation needs and nothing else. It is a *reader* only — nothing here
|
|
6
|
+
* encodes. It is strict where laxness would be a security hole:
|
|
7
|
+
*
|
|
8
|
+
* - Definite-length form only. Indefinite length (BER, `0x80`) is rejected.
|
|
9
|
+
* - A length that runs past the end of the buffer is rejected, never clamped.
|
|
10
|
+
* - Every accessor is bounds-checked and throws rather than returning a
|
|
11
|
+
* partial value.
|
|
12
|
+
*
|
|
13
|
+
* The one thing callers must be able to get at is the *raw* bytes of a node
|
|
14
|
+
* including its header, because a certificate signature covers the encoded
|
|
15
|
+
* `tbsCertificate`, not a re-encoding of its contents.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
/** DER tag numbers this module recognises. */
|
|
20
|
+
export const Tag = {
|
|
21
|
+
INTEGER: 0x02,
|
|
22
|
+
BIT_STRING: 0x03,
|
|
23
|
+
OCTET_STRING: 0x04,
|
|
24
|
+
NULL: 0x05,
|
|
25
|
+
OBJECT_IDENTIFIER: 0x06,
|
|
26
|
+
UTF8_STRING: 0x0c,
|
|
27
|
+
SEQUENCE: 0x30,
|
|
28
|
+
SET: 0x31,
|
|
29
|
+
UTC_TIME: 0x17,
|
|
30
|
+
GENERALIZED_TIME: 0x18,
|
|
31
|
+
BOOLEAN: 0x01,
|
|
32
|
+
};
|
|
33
|
+
/** Thrown for input that is not well-formed DER. */
|
|
34
|
+
export class DerError extends Error {
|
|
35
|
+
constructor(message) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "DerError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Reads one node at `offset`. */
|
|
41
|
+
export function readNode(buf, offset) {
|
|
42
|
+
if (offset >= buf.length) {
|
|
43
|
+
throw new DerError(`truncated: no tag byte at offset ${offset}`);
|
|
44
|
+
}
|
|
45
|
+
const tag = buf[offset];
|
|
46
|
+
let cursor = offset + 1;
|
|
47
|
+
if (cursor >= buf.length) {
|
|
48
|
+
throw new DerError(`truncated: no length byte at offset ${cursor}`);
|
|
49
|
+
}
|
|
50
|
+
const first = buf[cursor];
|
|
51
|
+
cursor += 1;
|
|
52
|
+
let length;
|
|
53
|
+
if (first < 0x80) {
|
|
54
|
+
// Short form: the byte is the length.
|
|
55
|
+
length = first;
|
|
56
|
+
}
|
|
57
|
+
else if (first === 0x80) {
|
|
58
|
+
throw new DerError("indefinite length is BER, not DER, and is not accepted here");
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
const byteCount = first & 0x7f;
|
|
62
|
+
// 4 bytes is 4 GiB; anything longer is either hostile or a parse desync.
|
|
63
|
+
// Stopping here also keeps the arithmetic below inside a safe integer.
|
|
64
|
+
if (byteCount > 4) {
|
|
65
|
+
throw new DerError(`length field of ${byteCount} bytes is unreasonable`);
|
|
66
|
+
}
|
|
67
|
+
if (cursor + byteCount > buf.length) {
|
|
68
|
+
throw new DerError("truncated: length field runs past the end");
|
|
69
|
+
}
|
|
70
|
+
length = 0;
|
|
71
|
+
for (let i = 0; i < byteCount; i += 1) {
|
|
72
|
+
length = length * 256 + buf[cursor + i];
|
|
73
|
+
}
|
|
74
|
+
cursor += byteCount;
|
|
75
|
+
}
|
|
76
|
+
const end = cursor + length;
|
|
77
|
+
if (end > buf.length) {
|
|
78
|
+
throw new DerError(`truncated: node at ${offset} claims ${length} content bytes but only ` +
|
|
79
|
+
`${buf.length - cursor} remain`);
|
|
80
|
+
}
|
|
81
|
+
return { tag, start: offset, contentStart: cursor, length, end };
|
|
82
|
+
}
|
|
83
|
+
/** Reads one node at `offset` and asserts its tag. */
|
|
84
|
+
export function readNodeOfTag(buf, offset, tag, what) {
|
|
85
|
+
const node = readNode(buf, offset);
|
|
86
|
+
if (node.tag !== tag) {
|
|
87
|
+
throw new DerError(`expected ${what} (tag 0x${tag.toString(16)}) at offset ${offset}, ` +
|
|
88
|
+
`found tag 0x${node.tag.toString(16)}`);
|
|
89
|
+
}
|
|
90
|
+
return node;
|
|
91
|
+
}
|
|
92
|
+
/** The node's content bytes, without its header. A view, not a copy. */
|
|
93
|
+
export function content(buf, node) {
|
|
94
|
+
return buf.subarray(node.contentStart, node.end);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The node's complete encoding, header included.
|
|
98
|
+
*
|
|
99
|
+
* This is what a signature covers. Re-encoding the parsed contents instead
|
|
100
|
+
* would be a bug: DER has canonical forms, but a signer's bytes are the only
|
|
101
|
+
* bytes that verify.
|
|
102
|
+
*/
|
|
103
|
+
export function raw(buf, node) {
|
|
104
|
+
return buf.subarray(node.start, node.end);
|
|
105
|
+
}
|
|
106
|
+
/** Every immediate child of a constructed node, in order. */
|
|
107
|
+
export function children(buf, node) {
|
|
108
|
+
const out = [];
|
|
109
|
+
let cursor = node.contentStart;
|
|
110
|
+
while (cursor < node.end) {
|
|
111
|
+
const child = readNode(buf, cursor);
|
|
112
|
+
out.push(child);
|
|
113
|
+
if (child.end <= cursor) {
|
|
114
|
+
throw new DerError("zero-length advance while walking children");
|
|
115
|
+
}
|
|
116
|
+
cursor = child.end;
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** The child at `index`, or `undefined` when the node has fewer children. */
|
|
121
|
+
export function childAt(buf, node, index) {
|
|
122
|
+
return children(buf, node)[index];
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Decodes an OBJECT IDENTIFIER to dotted-decimal form.
|
|
126
|
+
*
|
|
127
|
+
* The first byte packs two arcs: `40 * first + second`, with the first arc
|
|
128
|
+
* capped at 2. Every later arc is base-128 with the high bit as a
|
|
129
|
+
* continuation flag.
|
|
130
|
+
*/
|
|
131
|
+
export function readOid(buf, node) {
|
|
132
|
+
if (node.tag !== Tag.OBJECT_IDENTIFIER) {
|
|
133
|
+
throw new DerError(`expected OBJECT IDENTIFIER, found tag 0x${node.tag.toString(16)}`);
|
|
134
|
+
}
|
|
135
|
+
const bytes = content(buf, node);
|
|
136
|
+
if (bytes.length === 0)
|
|
137
|
+
throw new DerError("empty OBJECT IDENTIFIER");
|
|
138
|
+
const first = Math.min(Math.floor(bytes[0] / 40), 2);
|
|
139
|
+
const second = bytes[0] - first * 40;
|
|
140
|
+
const arcs = [first, second];
|
|
141
|
+
let value = 0;
|
|
142
|
+
let started = false;
|
|
143
|
+
for (let i = 1; i < bytes.length; i += 1) {
|
|
144
|
+
const byte = bytes[i];
|
|
145
|
+
// Guard against an arc wide enough to lose precision in a double.
|
|
146
|
+
if (value > Number.MAX_SAFE_INTEGER / 128) {
|
|
147
|
+
throw new DerError("OBJECT IDENTIFIER arc is too large");
|
|
148
|
+
}
|
|
149
|
+
value = value * 128 + (byte & 0x7f);
|
|
150
|
+
started = true;
|
|
151
|
+
if ((byte & 0x80) === 0) {
|
|
152
|
+
arcs.push(value);
|
|
153
|
+
value = 0;
|
|
154
|
+
started = false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (started) {
|
|
158
|
+
throw new DerError("OBJECT IDENTIFIER ends mid-arc");
|
|
159
|
+
}
|
|
160
|
+
return arcs.join(".");
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Decodes a BIT STRING's payload, dropping the unused-bits count byte.
|
|
164
|
+
*
|
|
165
|
+
* Every BIT STRING this module reads — a SubjectPublicKey, a certificate
|
|
166
|
+
* signature — is byte-aligned, so a non-zero unused-bits count means the
|
|
167
|
+
* parse has gone wrong and is rejected rather than shifted.
|
|
168
|
+
*/
|
|
169
|
+
export function readBitString(buf, node) {
|
|
170
|
+
if (node.tag !== Tag.BIT_STRING) {
|
|
171
|
+
throw new DerError(`expected BIT STRING, found tag 0x${node.tag.toString(16)}`);
|
|
172
|
+
}
|
|
173
|
+
const bytes = content(buf, node);
|
|
174
|
+
if (bytes.length === 0)
|
|
175
|
+
throw new DerError("empty BIT STRING");
|
|
176
|
+
const unused = bytes[0];
|
|
177
|
+
if (unused !== 0) {
|
|
178
|
+
throw new DerError(`BIT STRING has ${unused} unused bits; only byte-aligned values are supported`);
|
|
179
|
+
}
|
|
180
|
+
return bytes.subarray(1);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Decodes an INTEGER's magnitude with any DER sign padding removed.
|
|
184
|
+
*
|
|
185
|
+
* DER prepends a zero byte when the high bit would otherwise read as
|
|
186
|
+
* negative. ECDSA `r` and `s` are unsigned, so that byte must go before the
|
|
187
|
+
* value is padded to its fixed width.
|
|
188
|
+
*/
|
|
189
|
+
export function readUnsignedInteger(buf, node) {
|
|
190
|
+
if (node.tag !== Tag.INTEGER) {
|
|
191
|
+
throw new DerError(`expected INTEGER, found tag 0x${node.tag.toString(16)}`);
|
|
192
|
+
}
|
|
193
|
+
const bytes = content(buf, node);
|
|
194
|
+
if (bytes.length === 0)
|
|
195
|
+
throw new DerError("empty INTEGER");
|
|
196
|
+
if ((bytes[0] & 0x80) !== 0) {
|
|
197
|
+
throw new DerError("negative INTEGER where an unsigned value was expected");
|
|
198
|
+
}
|
|
199
|
+
let offset = 0;
|
|
200
|
+
while (offset < bytes.length - 1 && bytes[offset] === 0)
|
|
201
|
+
offset += 1;
|
|
202
|
+
return bytes.subarray(offset);
|
|
203
|
+
}
|
|
204
|
+
const TIME_PATTERN = /^(\d{2}|\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})?Z$/;
|
|
205
|
+
/**
|
|
206
|
+
* Decodes a UTCTime or GeneralizedTime to epoch milliseconds.
|
|
207
|
+
*
|
|
208
|
+
* Only the UTC (`Z`) form is accepted. Certificates may legally carry a
|
|
209
|
+
* numeric offset, but Apple's do not, and accepting one would mean
|
|
210
|
+
* hand-rolling timezone arithmetic for no gain.
|
|
211
|
+
*
|
|
212
|
+
* Per RFC 5280, a two-digit UTCTime year of 50 or more means 19xx, and less
|
|
213
|
+
* than 50 means 20xx.
|
|
214
|
+
*/
|
|
215
|
+
export function readTime(buf, node) {
|
|
216
|
+
if (node.tag !== Tag.UTC_TIME && node.tag !== Tag.GENERALIZED_TIME) {
|
|
217
|
+
throw new DerError(`expected UTCTime or GeneralizedTime, found tag 0x${node.tag.toString(16)}`);
|
|
218
|
+
}
|
|
219
|
+
const bytes = content(buf, node);
|
|
220
|
+
let text = "";
|
|
221
|
+
for (let i = 0; i < bytes.length; i += 1)
|
|
222
|
+
text += String.fromCharCode(bytes[i]);
|
|
223
|
+
const match = TIME_PATTERN.exec(text);
|
|
224
|
+
if (!match) {
|
|
225
|
+
throw new DerError(`unsupported time format: ${JSON.stringify(text)}`);
|
|
226
|
+
}
|
|
227
|
+
const [, rawYear, month, day, hour, minute, second] = match;
|
|
228
|
+
let year;
|
|
229
|
+
if (node.tag === Tag.UTC_TIME) {
|
|
230
|
+
if (rawYear.length !== 2) {
|
|
231
|
+
throw new DerError("UTCTime must carry a two-digit year");
|
|
232
|
+
}
|
|
233
|
+
const yy = Number(rawYear);
|
|
234
|
+
year = yy >= 50 ? 1900 + yy : 2000 + yy;
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
if (rawYear.length !== 4) {
|
|
238
|
+
throw new DerError("GeneralizedTime must carry a four-digit year");
|
|
239
|
+
}
|
|
240
|
+
year = Number(rawYear);
|
|
241
|
+
}
|
|
242
|
+
const ms = Date.UTC(year, Number(month) - 1, Number(day), Number(hour), Number(minute), second ? Number(second) : 0);
|
|
243
|
+
if (Number.isNaN(ms)) {
|
|
244
|
+
throw new DerError(`invalid time value: ${JSON.stringify(text)}`);
|
|
245
|
+
}
|
|
246
|
+
return ms;
|
|
247
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type AppleRoot } from "./apple-roots.js";
|
|
2
|
+
import { type Certificate } from "./x509.js";
|
|
3
|
+
/** How many certificates Apple puts in an `x5c` header. */
|
|
4
|
+
export declare const APPLE_CHAIN_LENGTH = 3;
|
|
5
|
+
/** Inputs to {@link verifyChain}. */
|
|
6
|
+
export interface VerifyChainOptions {
|
|
7
|
+
/**
|
|
8
|
+
* The instant to evaluate certificate validity at.
|
|
9
|
+
*
|
|
10
|
+
* With offline checks — the only mode v1 supports — this is the payload's own
|
|
11
|
+
* `signedDate`, matching Apple's library. That choice is what lets a
|
|
12
|
+
* captured payload stay verifiable forever, which in turn is what makes
|
|
13
|
+
* stored raw tokens a usable source of truth.
|
|
14
|
+
*/
|
|
15
|
+
readonly at: number;
|
|
16
|
+
/**
|
|
17
|
+
* Trust anchors to pin against. Defaults to Apple's real roots.
|
|
18
|
+
*
|
|
19
|
+
* Overridden only by this module's own tests, which mint a throwaway chain.
|
|
20
|
+
* It is deliberately not reachable from `IapConfig`: an app must never be
|
|
21
|
+
* able to add a root.
|
|
22
|
+
*/
|
|
23
|
+
readonly roots?: readonly AppleRoot[];
|
|
24
|
+
}
|
|
25
|
+
/** A validated chain. */
|
|
26
|
+
export interface VerifiedChain {
|
|
27
|
+
/** The leaf certificate, whose key signed the token itself. */
|
|
28
|
+
readonly leaf: Certificate;
|
|
29
|
+
/** The intermediate that issued the leaf. */
|
|
30
|
+
readonly intermediate: Certificate;
|
|
31
|
+
/** The pinned root the chain terminated at. */
|
|
32
|
+
readonly root: AppleRoot;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Validates a three-certificate Apple chain and returns the leaf.
|
|
36
|
+
*
|
|
37
|
+
* @param x5c - The certificates from the JWS header, leaf first.
|
|
38
|
+
* @throws {IapVerificationError} on any failure. There is no partial success.
|
|
39
|
+
*/
|
|
40
|
+
export declare function verifyChain(x5c: readonly Uint8Array[], options: VerifyChainOptions): Promise<VerifiedChain>;
|