@base44-preview/sdk 0.8.48-pr.145.de7eff3 → 0.8.48-pr.276.4f760f9

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.
Files changed (71) hide show
  1. package/dist/iap/account-token.d.ts +14 -0
  2. package/dist/iap/account-token.js +43 -0
  3. package/dist/iap/config.d.ts +18 -0
  4. package/dist/iap/config.js +99 -0
  5. package/dist/iap/errors.d.ts +89 -0
  6. package/dist/iap/errors.js +66 -0
  7. package/dist/iap/errors.types.d.ts +74 -0
  8. package/dist/iap/errors.types.js +7 -0
  9. package/dist/iap/events/emitter.d.ts +28 -0
  10. package/dist/iap/events/emitter.js +33 -0
  11. package/dist/iap/events/events.types.d.ts +124 -0
  12. package/dist/iap/events/events.types.js +1 -0
  13. package/dist/iap/iap.types.d.ts +618 -0
  14. package/dist/iap/iap.types.js +1 -0
  15. package/dist/iap/index.d.ts +120 -0
  16. package/dist/iap/index.js +140 -0
  17. package/dist/iap/ingest/device.d.ts +7 -0
  18. package/dist/iap/ingest/device.js +191 -0
  19. package/dist/iap/ingest/device.types.d.ts +80 -0
  20. package/dist/iap/ingest/device.types.js +1 -0
  21. package/dist/iap/ingest/mappers.d.ts +66 -0
  22. package/dist/iap/ingest/mappers.js +248 -0
  23. package/dist/iap/ingest/matrix.d.ts +55 -0
  24. package/dist/iap/ingest/matrix.js +202 -0
  25. package/dist/iap/ingest/notifications.d.ts +70 -0
  26. package/dist/iap/ingest/notifications.js +238 -0
  27. package/dist/iap/read/derive.d.ts +40 -0
  28. package/dist/iap/read/derive.js +112 -0
  29. package/dist/iap/read/read.d.ts +47 -0
  30. package/dist/iap/read/read.js +215 -0
  31. package/dist/iap/read/read.types.d.ts +174 -0
  32. package/dist/iap/read/read.types.js +1 -0
  33. package/dist/iap/runtime/base64.d.ts +34 -0
  34. package/dist/iap/runtime/base64.js +131 -0
  35. package/dist/iap/runtime/clock.d.ts +13 -0
  36. package/dist/iap/runtime/clock.js +11 -0
  37. package/dist/iap/runtime/webcrypto.d.ts +14 -0
  38. package/dist/iap/runtime/webcrypto.js +66 -0
  39. package/dist/iap/server-api/client.d.ts +16 -0
  40. package/dist/iap/server-api/client.js +140 -0
  41. package/dist/iap/server-api/jwt.d.ts +3 -0
  42. package/dist/iap/server-api/jwt.js +70 -0
  43. package/dist/iap/server-api/server-api.types.d.ts +155 -0
  44. package/dist/iap/server-api/server-api.types.js +12 -0
  45. package/dist/iap/store/collapse.d.ts +27 -0
  46. package/dist/iap/store/collapse.js +85 -0
  47. package/dist/iap/store/descriptors.d.ts +46 -0
  48. package/dist/iap/store/descriptors.js +90 -0
  49. package/dist/iap/store/entities-store.d.ts +43 -0
  50. package/dist/iap/store/entities-store.js +348 -0
  51. package/dist/iap/store/rows.types.d.ts +233 -0
  52. package/dist/iap/store/rows.types.js +1 -0
  53. package/dist/iap/store/schemas.d.ts +68 -0
  54. package/dist/iap/store/schemas.js +214 -0
  55. package/dist/iap/store/store-errors.d.ts +52 -0
  56. package/dist/iap/store/store-errors.js +103 -0
  57. package/dist/iap/store/store.types.d.ts +193 -0
  58. package/dist/iap/store/store.types.js +1 -0
  59. package/dist/iap/verify/apple-roots.d.ts +18 -0
  60. package/dist/iap/verify/apple-roots.js +121 -0
  61. package/dist/iap/verify/payload-checks.d.ts +30 -0
  62. package/dist/iap/verify/payload-checks.js +20 -0
  63. package/dist/iap/verify/verifier.d.ts +36 -0
  64. package/dist/iap/verify/verifier.js +161 -0
  65. package/dist/iap/verify/verify.types.d.ts +292 -0
  66. package/dist/iap/verify/verify.types.js +15 -0
  67. package/dist/iap/version.d.ts +13 -0
  68. package/dist/iap/version.js +13 -0
  69. package/dist/index.d.ts +11 -0
  70. package/dist/modules/functions.js +2 -6
  71. package/package.json +33 -3
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Apple in-app purchase support — the `@base44/sdk/iap` entry point.
3
+ *
4
+ * Kept behind its own subpath deliberately. Verification carries certificate
5
+ * parsing and cryptography that only a backend function ever runs, and the
6
+ * main entry point is imported by browsers and by React Native. The types are
7
+ * re-exported from `@base44/sdk` as well, where they cost nothing, so shared
8
+ * front-end code can name them without pulling any of this in.
9
+ */
10
+ import type { Base44Client } from "../client.types.js";
11
+ import type { AppleRoot } from "./verify/apple-roots.js";
12
+ import { type Clock } from "./runtime/clock.js";
13
+ import type { IapStoreMode } from "./store/store.types.js";
14
+ import type { IapConfig, IapModule } from "./iap.types.js";
15
+ /** Test seams. Not part of the public contract. @internal */
16
+ export interface IapInternalOptions {
17
+ /**
18
+ * Trust anchors to pin against, replacing Apple's real roots.
19
+ *
20
+ * For this SDK's own tests. An app must never be able to add a root, which
21
+ * is why this is not reachable from {@link IapConfig}.
22
+ */
23
+ readonly roots?: readonly AppleRoot[];
24
+ /** The clock. */
25
+ readonly clock?: Clock;
26
+ /**
27
+ * The `fetch` used for App Store Server API calls.
28
+ *
29
+ * Injected for tests: `nock` hooks Node's http module and does not intercept
30
+ * native `fetch`, which is what this client uses.
31
+ */
32
+ readonly fetchImpl?: typeof fetch;
33
+ /**
34
+ * How the store addresses rows.
35
+ *
36
+ * Defaults to `"query-guard"`, which is correct whether or not the backend
37
+ * honours a caller-supplied record id. `"natural-id"` is one round trip
38
+ * cheaper per insert, but only safe once that has been confirmed — on a
39
+ * backend that ignores the id, de-duplication would never fire.
40
+ */
41
+ readonly storeMode?: IapStoreMode;
42
+ }
43
+ /** Inputs to {@linkcode createIapClient | createIapClient()}. */
44
+ export interface CreateIapClientOptions {
45
+ /**
46
+ * A Base44 client from
47
+ * {@linkcode createClientFromRequest | createClientFromRequest()}.
48
+ *
49
+ * Purchase records are stored in the app's own entities with service-role
50
+ * access, so the client must come from an incoming backend-function request.
51
+ */
52
+ base44: Base44Client;
53
+ /** How the module behaves for this app. */
54
+ config: IapConfig;
55
+ /** @internal */
56
+ internal?: IapInternalOptions;
57
+ }
58
+ /**
59
+ * Creates the in-app purchase module for one app.
60
+ *
61
+ * Validates the configuration immediately and throws if it cannot be operated
62
+ * correctly, so a mistake surfaces on deploy rather than on Apple's first
63
+ * notification. Creating a client does no I/O, so building one per request is
64
+ * both correct and cheap.
65
+ *
66
+ * @param options - The Base44 client and the app's purchase configuration.
67
+ * @returns The in-app purchase module.
68
+ * @throws {Error} An `IapConfigError` when the configuration is invalid or asks for an unsupported option.
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * // Verify a purchase in a backend function
73
+ * import { createClientFromRequest } from "npm:@base44/sdk";
74
+ * import { createIapClient } from "npm:@base44/sdk/iap";
75
+ *
76
+ * Deno.serve(async (req) => {
77
+ * const iap = createIapClient({
78
+ * base44: createClientFromRequest(req),
79
+ * config: {
80
+ * bundleId: "com.example.app",
81
+ * appAppleId: 1234567890,
82
+ * products: { pro_monthly: { type: "autoRenewableSubscription" } },
83
+ * },
84
+ * });
85
+ *
86
+ * const { jws } = await req.json();
87
+ * const transaction = await iap.verifyTransaction(jws);
88
+ * return Response.json({ productId: transaction.productId });
89
+ * });
90
+ * ```
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // Accept sandbox purchases while testing
95
+ * const iap = createIapClient({
96
+ * base44,
97
+ * config: {
98
+ * bundleId: "com.example.app",
99
+ * appAppleId: 1234567890,
100
+ * products: { coins_100: { type: "consumable" } },
101
+ * testMode: true,
102
+ * },
103
+ * });
104
+ * ```
105
+ */
106
+ export declare function createIapClient(options: CreateIapClientOptions): IapModule;
107
+ export { appAccountTokenFor, IAP_APP_ACCOUNT_TOKEN_NAMESPACE } from "./account-token.js";
108
+ export { IapApiError, IapConfigError, IapError, IapSetupError, IapStoreError, IapVerificationError, } from "./errors.js";
109
+ export { IAP_MODULE_VERSION } from "./version.js";
110
+ export { IAP_ENTITY_NAMES, IAP_ENTITY_SCHEMAS, IAP_SETUP_CHECKLIST, } from "./store/schemas.js";
111
+ export type { IapConfig, IapConfiguredProductType, IapModule, IapProductConfig, IapSetupReport, } from "./iap.types.js";
112
+ export type { IapEvent, IapEventHandler, IapEventType, IapExpiryReason, IapRenewReason, IapStartReason, } from "./events/events.types.js";
113
+ export type { HandleNotificationResult } from "./ingest/notifications.js";
114
+ export type { ConsumptionRequestBody, IapDeliveryStatus, IapRefundPreference, IapServerApiConfig, IapServerApiModule, SendAttempt, SendAttemptResult, TestNotificationResult, TestNotificationStatus, } from "./server-api/server-api.types.js";
115
+ export type { RecordTransactionOptions, RecordTransactionResult, SyncPayload, SyncResult, } from "./ingest/device.types.js";
116
+ export type { EntitlementQuery, Entitlements, IapExpirationReason, IapRevocation, IapSubscriptionOffer, IapSubscriptionStatus, OwnedNonConsumable, OwnedNonRenewingSubscription, SubscriptionQuery, SubscriptionState, TransactionQuery, } from "./read/read.types.js";
117
+ export type { IapEntityName, IapEntitySchema, IapSchemaField, } from "./store/schemas.js";
118
+ export type { IapConsumptionOutcome, IapConsumptionRequestRecord, IapNotificationOutcome, IapNotificationRecord, IapRecordSource, IapSubscriptionRecord, IapTransactionRecord, } from "./store/rows.types.js";
119
+ export type { IapApiErrorCode, IapConfigErrorCode, IapSetupErrorCode, IapStoreErrorCode, IapVerificationErrorCode, } from "./errors.types.js";
120
+ export type { DecodedNotification, DecodedNotificationData, DecodedNotificationSummary, DecodedRenewalInfo, DecodedTransaction, IapAppleSubscriptionStatus, IapConsumptionRequestReason, IapEnvironment, IapExpirationIntent, IapOfferDiscountType, IapOfferType, IapOwnershipType, IapProductType, IapRevocationType, IapTransactionReason, } from "./verify/verify.types.js";
@@ -0,0 +1,140 @@
1
+ import { appAccountTokenFor } from "./account-token.js";
2
+ import { resolveConfig } from "./config.js";
3
+ import { createVerifier } from "./verify/verifier.js";
4
+ import { systemClock } from "./runtime/clock.js";
5
+ import { createEmitter } from "./events/emitter.js";
6
+ import { createEntitiesStore } from "./store/entities-store.js";
7
+ import { IAP_SETUP_CHECKLIST } from "./store/schemas.js";
8
+ import { handleNotification, handleSignedPayload, } from "./ingest/notifications.js";
9
+ import { createReader } from "./read/read.js";
10
+ import { createServerApiClient } from "./server-api/client.js";
11
+ import { recordTransaction, syncEntitlements } from "./ingest/device.js";
12
+ /**
13
+ * Creates the in-app purchase module for one app.
14
+ *
15
+ * Validates the configuration immediately and throws if it cannot be operated
16
+ * correctly, so a mistake surfaces on deploy rather than on Apple's first
17
+ * notification. Creating a client does no I/O, so building one per request is
18
+ * both correct and cheap.
19
+ *
20
+ * @param options - The Base44 client and the app's purchase configuration.
21
+ * @returns The in-app purchase module.
22
+ * @throws {Error} An `IapConfigError` when the configuration is invalid or asks for an unsupported option.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // Verify a purchase in a backend function
27
+ * import { createClientFromRequest } from "npm:@base44/sdk";
28
+ * import { createIapClient } from "npm:@base44/sdk/iap";
29
+ *
30
+ * Deno.serve(async (req) => {
31
+ * const iap = createIapClient({
32
+ * base44: createClientFromRequest(req),
33
+ * config: {
34
+ * bundleId: "com.example.app",
35
+ * appAppleId: 1234567890,
36
+ * products: { pro_monthly: { type: "autoRenewableSubscription" } },
37
+ * },
38
+ * });
39
+ *
40
+ * const { jws } = await req.json();
41
+ * const transaction = await iap.verifyTransaction(jws);
42
+ * return Response.json({ productId: transaction.productId });
43
+ * });
44
+ * ```
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * // Accept sandbox purchases while testing
49
+ * const iap = createIapClient({
50
+ * base44,
51
+ * config: {
52
+ * bundleId: "com.example.app",
53
+ * appAppleId: 1234567890,
54
+ * products: { coins_100: { type: "consumable" } },
55
+ * testMode: true,
56
+ * },
57
+ * });
58
+ * ```
59
+ */
60
+ export function createIapClient(options) {
61
+ var _a, _b, _c, _d, _e;
62
+ if (!options || !options.base44) {
63
+ throw new TypeError("createIapClient needs a Base44 client — create one with createClientFromRequest(request)");
64
+ }
65
+ const config = resolveConfig(options.config);
66
+ const clock = (_b = (_a = options.internal) === null || _a === void 0 ? void 0 : _a.clock) !== null && _b !== void 0 ? _b : systemClock;
67
+ const verifier = createVerifier({ config, roots: (_c = options.internal) === null || _c === void 0 ? void 0 : _c.roots });
68
+ const store = createEntitiesStore({
69
+ // Reached lazily: the service-role accessor throws when the client has no
70
+ // service credentials, and constructing an IAP client must not.
71
+ getEntities: () => options.base44.asServiceRole.entities,
72
+ mode: (_d = options.internal) === null || _d === void 0 ? void 0 : _d.storeMode,
73
+ clock,
74
+ });
75
+ const emitter = createEmitter();
76
+ const context = { store, verifier, config, clock, emitter };
77
+ const reader = createReader({
78
+ store,
79
+ verifier,
80
+ config,
81
+ clock,
82
+ report: (what, error) => {
83
+ // A read that failed is not the same as a customer with no purchases,
84
+ // and only one of the two is a problem. Saying so is what stops an app
85
+ // whose entities were never created from looking like an app with no
86
+ // paying customers.
87
+ console.warn(`[base44 iap] ${what}`, error instanceof Error ? error.message : error !== null && error !== void 0 ? error : "");
88
+ },
89
+ });
90
+ return {
91
+ verifyTransaction: verifier.verifyTransaction,
92
+ verifyRenewalInfo: verifier.verifyRenewalInfo,
93
+ verifyNotification: verifier.verifyNotification,
94
+ appAccountTokenFor,
95
+ serverApi: createServerApiClient({
96
+ config: config.serverApi,
97
+ bundleId: config.bundleId,
98
+ clock,
99
+ // A sandbox app's transactions live in the sandbox environment, so try
100
+ // it first there and save a round trip.
101
+ preferSandbox: config.testMode,
102
+ fetchImpl: (_e = options.internal) === null || _e === void 0 ? void 0 : _e.fetchImpl,
103
+ }),
104
+ hasActiveSubscription: reader.hasActiveSubscription,
105
+ getSubscriptionState: reader.getSubscriptionState,
106
+ getEntitlements: reader.getEntitlements,
107
+ getPurchase: reader.getPurchase,
108
+ listTransactions: reader.listTransactions,
109
+ listRefunds: reader.listRefunds,
110
+ listPendingConsumptionRequests: reader.listPendingConsumptionRequests,
111
+ recordTransaction: (jws, recordOptions) => recordTransaction(context, jws, recordOptions),
112
+ syncEntitlements: (payload, syncOptions) => syncEntitlements(context, reader, payload, syncOptions),
113
+ handleNotification: (request) => handleNotification(context, request),
114
+ handleSignedPayload: (signedPayload) => handleSignedPayload(context, signedPayload),
115
+ onEvent: (handler) => emitter.onEvent(handler),
116
+ async checkSetup() {
117
+ // Never throws: this is what a status page calls, and an app whose
118
+ // entities were never created looks identical to one with no customers.
119
+ try {
120
+ const health = await store.healthcheck();
121
+ return {
122
+ ok: health.ok,
123
+ missingEntities: health.missing,
124
+ checklist: IAP_SETUP_CHECKLIST,
125
+ };
126
+ }
127
+ catch (_a) {
128
+ return {
129
+ ok: false,
130
+ missingEntities: [],
131
+ checklist: IAP_SETUP_CHECKLIST,
132
+ };
133
+ }
134
+ },
135
+ };
136
+ }
137
+ export { appAccountTokenFor, IAP_APP_ACCOUNT_TOKEN_NAMESPACE } from "./account-token.js";
138
+ export { IapApiError, IapConfigError, IapError, IapSetupError, IapStoreError, IapVerificationError, } from "./errors.js";
139
+ export { IAP_MODULE_VERSION } from "./version.js";
140
+ export { IAP_ENTITY_NAMES, IAP_ENTITY_SCHEMAS, IAP_SETUP_CHECKLIST, } from "./store/schemas.js";
@@ -0,0 +1,7 @@
1
+ import type { Reader } from "../read/read.js";
2
+ import type { IngestContext } from "./notifications.js";
3
+ import type { RecordTransactionOptions, RecordTransactionResult, SyncPayload, SyncResult } from "./device.types.js";
4
+ /** Records a purchase the shell has just completed. */
5
+ export declare function recordTransaction(context: IngestContext, jws: string, options?: RecordTransactionOptions): Promise<RecordTransactionResult>;
6
+ /** Reconciles what the device knows against what the server knows. */
7
+ export declare function syncEntitlements(context: IngestContext, reader: Reader, payload: SyncPayload, options?: RecordTransactionOptions): Promise<SyncResult>;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * The two paths that start on the device.
3
+ *
4
+ * `recordTransaction` runs right after a purchase. Its contract with the shell
5
+ * is the important part: the shell must **not** call StoreKit's `finish()`
6
+ * until this resolves. An unfinished transaction is re-delivered at the next
7
+ * launch, so the device is the retry queue — and a purchase finished before
8
+ * the server stored it is a purchase nobody can prove.
9
+ *
10
+ * `syncEntitlements` runs at launch and on foreground. It is how everything
11
+ * heals: a notification Apple never managed to deliver, a purchase made on
12
+ * another device, a subscription that renewed while the app was closed.
13
+ *
14
+ * Both are idempotent.
15
+ *
16
+ * @internal
17
+ */
18
+ import { IapVerificationError } from "../errors.js";
19
+ import { SUBSCRIPTION_DESCRIPTOR, TRANSACTION_DESCRIPTOR, } from "../store/descriptors.js";
20
+ import { assertUserMatchesToken, subscriptionRenewalPatch, subscriptionRowFrom, subscriptionTransactionPatch, transactionPatchFrom, transactionRowFrom, } from "./mappers.js";
21
+ const SUBSCRIPTION_TYPE = "Auto-Renewable Subscription";
22
+ /** Whether a decoded transaction is an auto-renewable subscription. */
23
+ function isSubscription(decoded) {
24
+ return decoded.type === SUBSCRIPTION_TYPE;
25
+ }
26
+ /** Stores one verified transaction, and its subscription when it has one. */
27
+ async function storeTransaction(context, decoded, jws, appUserId, renewal) {
28
+ var _a;
29
+ const now = context.clock();
30
+ const row = transactionRowFrom(decoded, {
31
+ source: "device",
32
+ appUserId,
33
+ now,
34
+ config: context.config,
35
+ rawJws: jws,
36
+ });
37
+ const result = await context.store.upsertNewestWins(TRANSACTION_DESCRIPTOR, row.transactionId, { facet: "transaction", value: row.signedDate }, row, transactionPatchFrom(row));
38
+ if (isSubscription(decoded)) {
39
+ const subscriptionRow = subscriptionRowFrom({
40
+ transaction: decoded,
41
+ transactionJws: jws,
42
+ renewalInfoJws: renewal === null || renewal === void 0 ? void 0 : renewal.jws,
43
+ appUserId,
44
+ now,
45
+ });
46
+ // A bare device transaction carries no renewal information, so the row's
47
+ // renewal cursor is left alone and whatever a notification put there
48
+ // survives. That is why the two halves have separate cursors.
49
+ if ((renewal === null || renewal === void 0 ? void 0 : renewal.signedDate) != null) {
50
+ subscriptionRow.latestRenewalSignedDate = renewal.signedDate;
51
+ }
52
+ await context.store.upsertNewestWins(SUBSCRIPTION_DESCRIPTOR, subscriptionRow.originalTransactionId, { facet: "transaction", value: (_a = subscriptionRow.latestSignedDate) !== null && _a !== void 0 ? _a : now }, subscriptionRow, subscriptionTransactionPatch(subscriptionRow));
53
+ if (renewal && subscriptionRow.latestRenewalSignedDate !== null) {
54
+ await context.store.patchWhere(SUBSCRIPTION_DESCRIPTOR, subscriptionRow.originalTransactionId, {
55
+ cursorBelow: {
56
+ facet: "renewal",
57
+ value: subscriptionRow.latestRenewalSignedDate,
58
+ },
59
+ }, subscriptionRenewalPatch(subscriptionRow));
60
+ }
61
+ }
62
+ return { transactionId: row.transactionId, inserted: result.outcome === "inserted" };
63
+ }
64
+ /** Records a purchase the shell has just completed. */
65
+ export async function recordTransaction(context, jws, options = {}) {
66
+ var _a, _b;
67
+ const decoded = await context.verifier.verifyTransaction(jws);
68
+ const transactionId = decoded.transactionId;
69
+ if (typeof transactionId !== "string" || transactionId.length === 0) {
70
+ throw new IapVerificationError("INVALID_JWS_FORMAT", "the transaction carries no transactionId, so it cannot be stored or de-duplicated");
71
+ }
72
+ // The account token is a one-way hash of a user id, so it cannot be turned
73
+ // into one — but it can confirm a claim. Rejecting a mismatch is what stops
74
+ // one customer claiming another's purchase by replaying their token.
75
+ let appUserId = null;
76
+ if (options.appUserId) {
77
+ assertUserMatchesToken(decoded, options.appUserId);
78
+ appUserId = options.appUserId;
79
+ }
80
+ // Whether the row already existed is decided before the write, because that
81
+ // is what tells the app not to deliver a consumable twice.
82
+ const existing = await context.store.getByKey(TRANSACTION_DESCRIPTOR, transactionId, ["transactionId"]);
83
+ const duplicate = existing !== null;
84
+ // A throw here is deliberate and load-bearing: the shell must not call
85
+ // finish(), so StoreKit keeps the transaction and re-delivers it next launch.
86
+ await storeTransaction(context, decoded, jws, appUserId);
87
+ if (!duplicate) {
88
+ const event = {
89
+ type: isSubscription(decoded) ? "subscription.started" : "purchase.completed",
90
+ appUserId,
91
+ originalTransactionId: decoded.originalTransactionId
92
+ ? String(decoded.originalTransactionId)
93
+ : undefined,
94
+ transactionId,
95
+ productId: decoded.productId ? String(decoded.productId) : undefined,
96
+ environment: (_a = decoded.environment) !== null && _a !== void 0 ? _a : "Production",
97
+ occurredAt: Number((_b = decoded.signedDate) !== null && _b !== void 0 ? _b : context.clock()),
98
+ source: "device",
99
+ startReason: isSubscription(decoded) ? "initial" : undefined,
100
+ payload: decoded,
101
+ };
102
+ await context.emitter.emit([event]);
103
+ }
104
+ return { recorded: true, transactionId, duplicate, decoded };
105
+ }
106
+ /** Reconciles what the device knows against what the server knows. */
107
+ export async function syncEntitlements(context, reader, payload, options = {}) {
108
+ var _a, _b, _c, _d, _e;
109
+ const recordedTransactionIds = [];
110
+ const deviceProductIds = new Set();
111
+ let skipped = 0;
112
+ const appUserId = (_a = options.appUserId) !== null && _a !== void 0 ? _a : null;
113
+ /** Verifies and stores one token, counting rather than throwing on failure. */
114
+ async function ingest(jws, renewal) {
115
+ let decoded;
116
+ try {
117
+ decoded = await context.verifier.verifyTransaction(jws);
118
+ if (appUserId)
119
+ assertUserMatchesToken(decoded, appUserId);
120
+ }
121
+ catch (_a) {
122
+ // One unusable token must never fail the whole sync: the rest of the
123
+ // device's purchases are still real and still need storing.
124
+ skipped += 1;
125
+ return;
126
+ }
127
+ if (typeof decoded.productId === "string") {
128
+ deviceProductIds.add(decoded.productId);
129
+ }
130
+ try {
131
+ const stored = await storeTransaction(context, decoded, jws, appUserId, renewal);
132
+ // Reported only when it is durably stored, so the shell only finishes a
133
+ // transaction the server can prove.
134
+ recordedTransactionIds.push(stored.transactionId);
135
+ }
136
+ catch (_b) {
137
+ skipped += 1;
138
+ }
139
+ }
140
+ for (const jws of (_b = payload.entitlements) !== null && _b !== void 0 ? _b : [])
141
+ await ingest(jws);
142
+ for (const jws of (_c = payload.unfinished) !== null && _c !== void 0 ? _c : [])
143
+ await ingest(jws);
144
+ for (const pair of (_d = payload.statuses) !== null && _d !== void 0 ? _d : []) {
145
+ let renewalSignedDate = null;
146
+ try {
147
+ const renewal = await context.verifier.verifyRenewalInfo(pair.renewalInfoJws);
148
+ renewalSignedDate =
149
+ typeof renewal.signedDate === "number" ? renewal.signedDate : null;
150
+ }
151
+ catch (_f) {
152
+ skipped += 1;
153
+ }
154
+ await ingest(pair.transactionJws, {
155
+ jws: pair.renewalInfoJws,
156
+ signedDate: renewalSignedDate,
157
+ });
158
+ }
159
+ const snapshot = appUserId
160
+ ? await reader.getEntitlements(appUserId)
161
+ : { nonConsumables: [], nonRenewingSubscriptions: [], subscriptions: [], asOf: context.clock() };
162
+ // What the device thinks it owns that the server does not agree is live.
163
+ // Persistently above zero means notifications are going missing.
164
+ const serverProductIds = new Set();
165
+ for (const item of snapshot.nonConsumables)
166
+ serverProductIds.add(item.productId);
167
+ for (const item of snapshot.nonRenewingSubscriptions) {
168
+ if (item.active)
169
+ serverProductIds.add(item.productId);
170
+ }
171
+ for (const state of snapshot.subscriptions) {
172
+ if (state.entitled && state.productId)
173
+ serverProductIds.add(state.productId);
174
+ }
175
+ let mismatches = 0;
176
+ for (const productId of deviceProductIds) {
177
+ if (!serverProductIds.has(productId))
178
+ mismatches += 1;
179
+ }
180
+ await context.emitter.emit([
181
+ {
182
+ type: "sync.applied",
183
+ appUserId,
184
+ environment: (_e = payload.environment) !== null && _e !== void 0 ? _e : "Production",
185
+ occurredAt: context.clock(),
186
+ source: "device",
187
+ mismatches,
188
+ },
189
+ ]);
190
+ return { recordedTransactionIds, snapshot, mismatches, skipped };
191
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * What the native shell sends the backend.
3
+ *
4
+ * Two calls, both from the shell rather than the web app: one when a purchase
5
+ * completes, and one at launch to reconcile whatever the device knows against
6
+ * whatever the server knows. The web app never sends purchase tokens itself.
7
+ */
8
+ import type { DecodedTransaction, IapEnvironment } from "../verify/verify.types.js";
9
+ import type { Entitlements } from "../read/read.types.js";
10
+ /** Extra context for recording a purchase. */
11
+ export interface RecordTransactionOptions {
12
+ /**
13
+ * The Base44 user making the request.
14
+ *
15
+ * When given, it is checked against the UUID Apple signed into the
16
+ * transaction, and the call is rejected if they disagree — so one customer
17
+ * cannot claim another's purchase by replaying their token.
18
+ */
19
+ appUserId?: string;
20
+ }
21
+ /** What recording a purchase did. */
22
+ export interface RecordTransactionResult {
23
+ /** Whether the purchase is now stored. Always true when this resolves. */
24
+ recorded: boolean;
25
+ /** Apple's transaction id. */
26
+ transactionId: string;
27
+ /**
28
+ * Whether this transaction was already stored.
29
+ *
30
+ * The double-delivery guard. StoreKit re-delivers an unfinished transaction
31
+ * at every launch, so a consumable must only be granted when this is
32
+ * `false`.
33
+ */
34
+ duplicate: boolean;
35
+ /** The verified contents of the token. */
36
+ decoded: DecodedTransaction;
37
+ }
38
+ /** What the shell knows about the device's purchases. */
39
+ export interface SyncPayload {
40
+ /** Signed transactions from StoreKit's current entitlements. */
41
+ entitlements?: string[];
42
+ /** Signed transactions StoreKit still considers unfinished. */
43
+ unfinished?: string[];
44
+ /**
45
+ * Subscription status pairs, one per subscription group.
46
+ *
47
+ * The pairing matters: current entitlements carry a transaction but no
48
+ * renewal information, and renewal information is where the grace period and
49
+ * the auto-renew flag live.
50
+ */
51
+ statuses?: {
52
+ transactionJws: string;
53
+ renewalInfoJws: string;
54
+ }[];
55
+ /** The signed app transaction, if the shell has one. */
56
+ appTransaction?: string;
57
+ /** Which environment the device is in. */
58
+ environment?: IapEnvironment;
59
+ }
60
+ /** What a sync did. */
61
+ export interface SyncResult {
62
+ /**
63
+ * Transactions that are now durably stored.
64
+ *
65
+ * The shell may call `finish()` on these once it has delivered the content.
66
+ * An id missing from this list was not stored, so StoreKit should keep
67
+ * re-delivering it.
68
+ */
69
+ recordedTransactionIds: string[];
70
+ /** What the server believes the user owns, so the app can reconcile its UI. */
71
+ snapshot: Entitlements;
72
+ /**
73
+ * How many device entitlements the server did not know about, or disagreed on.
74
+ *
75
+ * Persistently above zero means notifications are being missed.
76
+ */
77
+ mismatches: number;
78
+ /** How many tokens failed verification and were skipped. */
79
+ skipped: number;
80
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
1
+ import type { ResolvedIapConfig } from "../config.js";
2
+ import type { DecodedNotification, DecodedRenewalInfo, DecodedTransaction, IapEnvironment } from "../verify/verify.types.js";
3
+ import type { IapConsumptionRequestRecord, IapNotificationRecord, IapRecordSource, IapSubscriptionRecord, IapTransactionRecord } from "../store/rows.types.js";
4
+ import type { IapPatch } from "../store/store.types.js";
5
+ /** Apple's window for consumption data: 12 hours live, 5 minutes in sandbox. */
6
+ export declare function consumptionDeadline(receivedAt: number, environment: IapEnvironment): number;
7
+ /**
8
+ * Confirms a claimed user matches the UUID Apple signed into the transaction.
9
+ *
10
+ * @throws {IapVerificationError} when the token belongs to a different user.
11
+ */
12
+ export declare function assertUserMatchesToken(decoded: DecodedTransaction, claimedUserId: string): void;
13
+ /** Builds a complete transaction row, for an insert. */
14
+ export declare function transactionRowFrom(decoded: DecodedTransaction, context: {
15
+ readonly source: IapRecordSource;
16
+ readonly appUserId: string | null;
17
+ readonly now: number;
18
+ readonly config: ResolvedIapConfig;
19
+ readonly rawJws: string;
20
+ }): IapTransactionRecord;
21
+ /** Builds the merge for an existing transaction row. */
22
+ export declare function transactionPatchFrom(row: IapTransactionRecord, options?: {
23
+ readonly clearRevocation?: boolean;
24
+ }): IapPatch<IapTransactionRecord>;
25
+ /** Builds a complete subscription row, for an insert. */
26
+ export declare function subscriptionRowFrom(context: {
27
+ readonly transaction: DecodedTransaction;
28
+ readonly transactionJws: string;
29
+ readonly renewalInfo?: DecodedRenewalInfo;
30
+ readonly renewalInfoJws?: string;
31
+ readonly appUserId: string | null;
32
+ readonly appleStatus?: IapSubscriptionRecord["appleStatus"];
33
+ readonly now: number;
34
+ }): IapSubscriptionRecord;
35
+ /**
36
+ * The transaction half of a subscription merge.
37
+ *
38
+ * Deliberately excludes the renewal columns. They have their own cursor,
39
+ * because a device sync brings a fresh transaction with no renewal
40
+ * information — and if one cursor covered both, that sync would advance past a
41
+ * later notification carrying a new grace-period date, denying service to a
42
+ * customer Apple is still trying to bill.
43
+ */
44
+ export declare function subscriptionTransactionPatch(row: IapSubscriptionRecord): IapPatch<IapSubscriptionRecord>;
45
+ /** The renewal half of a subscription merge, guarded by its own cursor. */
46
+ export declare function subscriptionRenewalPatch(row: IapSubscriptionRecord): IapPatch<IapSubscriptionRecord>;
47
+ /**
48
+ * Builds a notification row, claimed but not yet applied.
49
+ *
50
+ * `outcome: "error"` is the commit flag. Duplicate detection only treats a row
51
+ * as already handled once the outcome is something else, so a delivery whose
52
+ * writes failed after this row landed is re-applied on Apple's retry rather
53
+ * than dismissed as a duplicate — which would lose it for good, because Apple
54
+ * stops retrying once it sees success.
55
+ */
56
+ export declare function notificationRowFrom(context: {
57
+ readonly notification: DecodedNotification;
58
+ readonly rawSignedPayload: string;
59
+ readonly now: number;
60
+ }): IapNotificationRecord;
61
+ /** Builds a consumption-request row from a `CONSUMPTION_REQUEST` notification. */
62
+ export declare function consumptionRowFrom(context: {
63
+ readonly notification: DecodedNotification;
64
+ readonly appUserId: string | null;
65
+ readonly now: number;
66
+ }): IapConsumptionRequestRecord | null;