backend-manager 5.0.109 → 5.0.111

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/CHANGELOG.md CHANGED
@@ -14,6 +14,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
14
14
  - `Fixed` for any bug fixes.
15
15
  - `Security` in case of vulnerabilities.
16
16
 
17
+ # [5.0.109] - 2026-03-04
18
+ ### Added
19
+ - Immediate trial cancellation: cancelling during a free trial now terminates the subscription instantly instead of scheduling cancel at period end, preventing free premium access for the remainder of the trial.
20
+ - Intent status tracking: `payments-intents/{orderId}` is now updated with `status: completed/failed` and completion timestamp after webhook processing.
21
+ - `journey-payments-trial-cancel` test suite covering the full trial → cancel → immediate cancellation flow.
22
+
23
+ ### Changed
24
+ - Stripe and test cancel processors now detect trialing state and dispatch immediate cancel (`customer.subscription.deleted`) vs period-end cancel (`customer.subscription.updated`).
25
+
17
26
  # [5.0.106] - 2026-03-04
18
27
  ### Added
19
28
  - `GET /payments/trial-eligibility`: returns whether the authenticated user is eligible for a free trial (checks for any previous subscription orders in `payments-orders`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "5.0.109",
3
+ "version": "5.0.111",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -236,7 +236,18 @@ async function processPaymentEvent({ category, library, resource, resourceType,
236
236
 
237
237
  // Write to payments-orders/{orderId}
238
238
  if (orderId) {
239
- await admin.firestore().doc(`payments-orders/${orderId}`).set(order, { merge: true });
239
+ const orderRef = admin.firestore().doc(`payments-orders/${orderId}`);
240
+ const orderSnap = await orderRef.get();
241
+
242
+ // Initialize requests on first creation only (avoid overwriting cancel/refund data set by endpoints)
243
+ if (!orderSnap.exists) {
244
+ order.requests = {
245
+ cancellation: null,
246
+ refund: null,
247
+ };
248
+ }
249
+
250
+ await orderRef.set(order, { merge: true });
240
251
  assistant.log(`Updated payments-orders/${orderId}: type=${category}, uid=${uid}, eventType=${eventType}`);
241
252
  }
242
253
 
@@ -138,6 +138,9 @@ Manager.prototype.init = function (exporter, options) {
138
138
  (_objValue, srcValue) => isArray(srcValue) ? srcValue : undefined,
139
139
  );
140
140
 
141
+ // Set PAYPAL_CLIENT_ID from config (clientId is public, not a secret — lives in config, not .env)
142
+ process.env.PAYPAL_CLIENT_ID = process.env.PAYPAL_CLIENT_ID || self.config?.payment?.processors?.paypal?.clientId || '';
143
+
141
144
  // Resolve legacy paths
142
145
  // TODO: Remove this in future versions (after we migrate to removing app.id from config)
143
146
  self.config.app = self.config.app || {};
@@ -8,12 +8,41 @@ const EPOCH_ZERO_UNIX = powertools.timestamp(EPOCH_ZERO, { output: 'unix' });
8
8
  const INTERVAL_TO_FREQUENCY = { YEAR: 'annually', MONTH: 'monthly', WEEK: 'weekly', DAY: 'daily' };
9
9
  const FREQUENCY_TO_INTERVAL = { annually: 'YEAR', monthly: 'MONTH', weekly: 'WEEK', daily: 'DAY' };
10
10
 
11
- // PayPal API base URL
12
- const PAYPAL_API_BASE = 'https://api-m.paypal.com';
11
+ // PayPal API base URLs
12
+ const LIVE_URL = 'https://api-m.paypal.com';
13
+ const SANDBOX_URL = 'https://api-m.sandbox.paypal.com';
13
14
 
14
- // Cached access token + expiry
15
+ // Cached access token, expiry, and resolved base URL
15
16
  let cachedToken = null;
16
17
  let tokenExpiresAt = 0;
18
+ let resolvedBaseUrl = null;
19
+
20
+ /**
21
+ * Try to authenticate against a specific PayPal endpoint
22
+ * @param {string} auth - Base64-encoded client_id:secret
23
+ * @param {string} baseUrl - PayPal API base URL
24
+ * @returns {Promise<object|null>} Token data or null if auth failed
25
+ */
26
+ async function tryAuth(auth, baseUrl) {
27
+ try {
28
+ const response = await fetch(`${baseUrl}/v1/oauth2/token`, {
29
+ method: 'POST',
30
+ headers: {
31
+ 'Authorization': `Basic ${auth}`,
32
+ 'Content-Type': 'application/x-www-form-urlencoded',
33
+ },
34
+ body: 'grant_type=client_credentials',
35
+ });
36
+
37
+ if (!response.ok) {
38
+ return null;
39
+ }
40
+
41
+ return await response.json();
42
+ } catch (e) {
43
+ return null;
44
+ }
45
+ }
17
46
 
18
47
  /**
19
48
  * PayPal shared library
@@ -22,7 +51,7 @@ let tokenExpiresAt = 0;
22
51
  const PayPal = {
23
52
  /**
24
53
  * Initialize or return a PayPal access token
25
- * Uses client credentials grant (client_id + secret)
54
+ * Tries both live and sandbox endpoints in parallel on first auth
26
55
  * @returns {Promise<string>} Access token
27
56
  */
28
57
  async init() {
@@ -40,22 +69,39 @@ const PayPal = {
40
69
 
41
70
  const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
42
71
 
43
- const response = await fetch(`${PAYPAL_API_BASE}/v1/oauth2/token`, {
44
- method: 'POST',
45
- headers: {
46
- 'Authorization': `Basic ${auth}`,
47
- 'Content-Type': 'application/x-www-form-urlencoded',
48
- },
49
- body: 'grant_type=client_credentials',
50
- });
72
+ // First auth try both endpoints in parallel to detect environment
73
+ if (!resolvedBaseUrl) {
74
+ const [liveResult, sandboxResult] = await Promise.all([
75
+ tryAuth(auth, LIVE_URL),
76
+ tryAuth(auth, SANDBOX_URL),
77
+ ]);
78
+
79
+ if (liveResult) {
80
+ resolvedBaseUrl = LIVE_URL;
81
+ cachedToken = liveResult.access_token;
82
+ tokenExpiresAt = Date.now() + (liveResult.expires_in * 1000);
83
+ return cachedToken;
84
+ }
51
85
 
52
- if (!response.ok) {
53
- throw new Error(`PayPal auth failed: ${response.status} ${response.statusText}`);
86
+ if (sandboxResult) {
87
+ resolvedBaseUrl = SANDBOX_URL;
88
+ cachedToken = sandboxResult.access_token;
89
+ tokenExpiresAt = Date.now() + (sandboxResult.expires_in * 1000);
90
+ return cachedToken;
91
+ }
92
+
93
+ throw new Error('PayPal auth failed on both live and sandbox — check your client ID and secret');
54
94
  }
55
95
 
56
- const data = await response.json();
57
- cachedToken = data.access_token;
58
- tokenExpiresAt = Date.now() + (data.expires_in * 1000);
96
+ // Subsequent auths use the resolved endpoint
97
+ const result = await tryAuth(auth, resolvedBaseUrl);
98
+
99
+ if (!result) {
100
+ throw new Error(`PayPal auth failed (${resolvedBaseUrl})`);
101
+ }
102
+
103
+ cachedToken = result.access_token;
104
+ tokenExpiresAt = Date.now() + (result.expires_in * 1000);
59
105
 
60
106
  return cachedToken;
61
107
  },
@@ -69,7 +115,7 @@ const PayPal = {
69
115
  async request(endpoint, options = {}) {
70
116
  const token = await this.init();
71
117
 
72
- const response = await fetch(`${PAYPAL_API_BASE}${endpoint}`, {
118
+ const response = await fetch(`${resolvedBaseUrl}${endpoint}`, {
73
119
  ...options,
74
120
  headers: {
75
121
  'Authorization': `Bearer ${token}`,
@@ -1,4 +1,5 @@
1
1
  const path = require('path');
2
+ const powertools = require('node-powertools');
2
3
 
3
4
  /**
4
5
  * POST /payments/cancel
@@ -6,6 +7,7 @@ const path = require('path');
6
7
  * Delegates to the processor (e.g., Stripe) to set cancel_at_period_end=true.
7
8
  * The resulting webhook triggers the Firestore pipeline which updates subscription state
8
9
  * and fires the cancellation-requested transition handler.
10
+ * Stores the cancellation reason/feedback on payments-orders/{orderId}.requests.cancellation.
9
11
  * Requires authentication.
10
12
  */
11
13
  module.exports = async ({ assistant, user, settings }) => {
@@ -60,7 +62,31 @@ module.exports = async ({ assistant, user, settings }) => {
60
62
  return assistant.respond(`Failed to cancel subscription: ${e.message}`, { code: 500, sentry: true });
61
63
  }
62
64
 
63
- assistant.log(`Cancel at period end scheduled: uid=${uid}, processor=${processor}, sub=${resourceId}, reason=${settings.reason}`);
65
+ // Store cancellation reason/feedback on the order doc
66
+ const orderId = subscription.payment?.orderId;
67
+
68
+ if (orderId) {
69
+ const admin = assistant.Manager.libraries.admin;
70
+ const now = powertools.timestamp(new Date(), { output: 'string' });
71
+ const nowUNIX = powertools.timestamp(now, { output: 'unix' });
72
+
73
+ await admin.firestore().doc(`payments-orders/${orderId}`).set({
74
+ requests: {
75
+ cancellation: {
76
+ reason: settings.reason || null,
77
+ feedback: settings.feedback || null,
78
+ date: {
79
+ timestamp: now,
80
+ timestampUNIX: nowUNIX,
81
+ },
82
+ },
83
+ },
84
+ }, { merge: true });
85
+
86
+ assistant.log(`Stored cancellation request on payments-orders/${orderId}: reason=${settings.reason}`);
87
+ }
88
+
89
+ assistant.log(`Cancel scheduled: uid=${uid}, processor=${processor}, sub=${resourceId}, reason=${settings.reason}`);
64
90
 
65
91
  return assistant.respond({ success: true });
66
92
  };
@@ -1,4 +1,5 @@
1
1
  const path = require('path');
2
+ const powertools = require('node-powertools');
2
3
 
3
4
  /**
4
5
  * POST /payments/refund
@@ -8,6 +9,7 @@ const path = require('path');
8
9
  * Delegates to the processor (e.g., Stripe) to issue the refund and cancel.
9
10
  * The resulting webhook triggers the Firestore pipeline which updates subscription state
10
11
  * and fires the subscription-cancelled transition handler.
12
+ * Stores the refund reason/feedback on payments-orders/{orderId}.requests.refund.
11
13
  * Requires authentication.
12
14
  */
13
15
  module.exports = async ({ assistant, user, settings }) => {
@@ -79,6 +81,32 @@ module.exports = async ({ assistant, user, settings }) => {
79
81
  return assistant.respond(`Failed to process refund: ${e.message}`, { code: 500, sentry: true });
80
82
  }
81
83
 
84
+ // Store refund reason/feedback on the order doc
85
+ const orderId = subscription.payment?.orderId;
86
+
87
+ if (orderId) {
88
+ const admin = assistant.Manager.libraries.admin;
89
+ const now = powertools.timestamp(new Date(), { output: 'string' });
90
+ const nowUNIX = powertools.timestamp(now, { output: 'unix' });
91
+
92
+ await admin.firestore().doc(`payments-orders/${orderId}`).set({
93
+ requests: {
94
+ refund: {
95
+ reason: settings.reason || null,
96
+ feedback: settings.feedback || null,
97
+ amount: refund.amount,
98
+ full: refund.full,
99
+ date: {
100
+ timestamp: now,
101
+ timestampUNIX: nowUNIX,
102
+ },
103
+ },
104
+ },
105
+ }, { merge: true });
106
+
107
+ assistant.log(`Stored refund request on payments-orders/${orderId}: reason=${settings.reason}, amount=${refund.amount}`);
108
+ }
109
+
82
110
  assistant.log(`Refund processed: uid=${uid}, processor=${processor}, sub=${resourceId}, amount=${refund.amount}, full=${refund.full}, reason=${settings.reason}`);
83
111
 
84
112
  return assistant.respond({ success: true, refund });
@@ -75,5 +75,20 @@ module.exports = {
75
75
  assert.ok(userDoc.subscription.cancellation.date.timestampUNIX > 0, 'Cancellation date should be set');
76
76
  },
77
77
  },
78
+
79
+ {
80
+ name: 'cancellation-request-stored',
81
+ async run({ firestore, assert, state }) {
82
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
83
+
84
+ assert.ok(orderDoc, 'Order doc should exist');
85
+ assert.ok(orderDoc.requests, 'requests field should exist');
86
+ assert.ok(orderDoc.requests.cancellation, 'requests.cancellation should be populated');
87
+ assert.equal(orderDoc.requests.cancellation.reason, 'Too expensive', 'Cancellation reason should match');
88
+ assert.equal(orderDoc.requests.cancellation.feedback, 'Would return at a lower price', 'Cancellation feedback should match');
89
+ assert.ok(orderDoc.requests.cancellation.date.timestampUNIX > 0, 'Cancellation date should be set');
90
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should still be null');
91
+ },
92
+ },
78
93
  ],
79
94
  };
@@ -148,5 +148,31 @@ module.exports = {
148
148
  assert.equal(userDoc.subscription.cancellation.pending, false, 'Cancellation should not be pending');
149
149
  },
150
150
  },
151
+
152
+ {
153
+ name: 'order-doc-verified',
154
+ async run({ firestore, assert, state }) {
155
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
156
+
157
+ assert.ok(orderDoc, 'Order doc should exist');
158
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
159
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
160
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
161
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null (cancel was via webhook, not endpoint)');
162
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
163
+ },
164
+ },
165
+
166
+ {
167
+ name: 'intent-doc-completed',
168
+ async run({ firestore, assert, state }) {
169
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
170
+
171
+ assert.ok(intentDoc, 'Intent doc should exist');
172
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
173
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
174
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
175
+ },
176
+ },
151
177
  ],
152
178
  };
@@ -112,5 +112,31 @@ module.exports = {
112
112
  assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
113
113
  },
114
114
  },
115
+
116
+ {
117
+ name: 'order-doc-verified',
118
+ async run({ firestore, assert, state }) {
119
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
120
+
121
+ assert.ok(orderDoc, 'Order doc should exist');
122
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
123
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
124
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
125
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
126
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
127
+ },
128
+ },
129
+
130
+ {
131
+ name: 'intent-doc-completed',
132
+ async run({ firestore, assert, state }) {
133
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
134
+
135
+ assert.ok(intentDoc, 'Intent doc should exist');
136
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
137
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after initial webhook processing');
138
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
139
+ },
140
+ },
115
141
  ],
116
142
  };
@@ -85,6 +85,9 @@ module.exports = {
85
85
  assert.equal(orderDoc.type, 'one-time', 'Type should be one-time');
86
86
  assert.equal(orderDoc.owner, state.uid, 'Owner should match');
87
87
  assert.equal(orderDoc.processor, 'test', 'Processor should be test');
88
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
89
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
90
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
88
91
  },
89
92
  },
90
93
 
@@ -88,6 +88,9 @@ module.exports = {
88
88
  assert.equal(orderDoc.unified.product.id, state.productId, `Product should be ${state.productId}`);
89
89
  assert.equal(orderDoc.unified.payment.processor, 'test', 'Unified processor should be test');
90
90
  assert.equal(orderDoc.unified.payment.orderId, state.orderId, 'Unified orderId should match');
91
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
92
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
93
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
91
94
  },
92
95
  },
93
96
 
@@ -120,6 +120,21 @@ module.exports = {
120
120
  assert.ok(orderDoc, 'Order doc should exist');
121
121
  assert.equal(orderDoc.unified.product.id, state.productB.id, `Order product should be ${state.productB.id}`);
122
122
  assert.equal(orderDoc.unified.status, 'active', 'Order status should be active');
123
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
124
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
125
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
126
+ },
127
+ },
128
+
129
+ {
130
+ name: 'intent-doc-completed',
131
+ async run({ firestore, assert, state }) {
132
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
133
+
134
+ assert.ok(intentDoc, 'Intent doc should exist');
135
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
136
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
137
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
123
138
  },
124
139
  },
125
140
  ],
@@ -147,5 +147,31 @@ module.exports = {
147
147
  assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
148
148
  },
149
149
  },
150
+
151
+ {
152
+ name: 'order-doc-verified',
153
+ async run({ firestore, assert, state }) {
154
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
155
+
156
+ assert.ok(orderDoc, 'Order doc should exist');
157
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
158
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
159
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
160
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
161
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
162
+ },
163
+ },
164
+
165
+ {
166
+ name: 'intent-doc-completed',
167
+ async run({ firestore, assert, state }) {
168
+ const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
169
+
170
+ assert.ok(intentDoc, 'Intent doc should exist');
171
+ assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
172
+ assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
173
+ assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
174
+ },
175
+ },
150
176
  ],
151
177
  };
@@ -105,5 +105,20 @@ module.exports = {
105
105
  assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
106
106
  },
107
107
  },
108
+
109
+ {
110
+ name: 'cancellation-request-stored',
111
+ async run({ firestore, assert, state }) {
112
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
113
+
114
+ assert.ok(orderDoc, 'Order doc should exist');
115
+ assert.ok(orderDoc.requests, 'requests field should exist');
116
+ assert.ok(orderDoc.requests.cancellation, 'requests.cancellation should be populated');
117
+ assert.equal(orderDoc.requests.cancellation.reason, 'Changed my mind during trial', 'Cancellation reason should match');
118
+ assert.equal(orderDoc.requests.cancellation.feedback, 'Testing trial cancellation', 'Cancellation feedback should match');
119
+ assert.ok(orderDoc.requests.cancellation.date.timestampUNIX > 0, 'Cancellation date should be set');
120
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should still be null');
121
+ },
122
+ },
108
123
  ],
109
124
  };
@@ -91,6 +91,23 @@ module.exports = {
91
91
  },
92
92
  },
93
93
 
94
+ {
95
+ name: 'order-doc-created',
96
+ async run({ firestore, assert, state }) {
97
+ const orderDoc = await firestore.get(`payments-orders/${state.orderId}`);
98
+
99
+ assert.ok(orderDoc, 'Order doc should exist');
100
+ assert.equal(orderDoc.id, state.orderId, 'ID should match orderId');
101
+ assert.equal(orderDoc.type, 'subscription', 'Type should be subscription');
102
+ assert.equal(orderDoc.owner, state.uid, 'Owner should match');
103
+ assert.equal(orderDoc.unified.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
104
+ assert.equal(orderDoc.unified.trial.claimed, true, 'Trial should be claimed');
105
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
106
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null');
107
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null');
108
+ },
109
+ },
110
+
94
111
  {
95
112
  name: 'send-trial-to-active-webhook',
96
113
  async run({ http, assert, state, config }) {
@@ -90,6 +90,9 @@ module.exports = {
90
90
  assert.equal(orderDoc.resourceId, state.subscriptionId, 'Resource ID should match');
91
91
  assert.equal(orderDoc.unified.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
92
92
  assert.equal(orderDoc.unified.status, 'active', 'Status should be active');
93
+ assert.ok(orderDoc.requests !== undefined, 'requests field should exist');
94
+ assert.equal(orderDoc.requests.cancellation, null, 'requests.cancellation should be null initially');
95
+ assert.equal(orderDoc.requests.refund, null, 'requests.refund should be null initially');
93
96
  },
94
97
  },
95
98