backend-manager 5.0.107 → 5.0.109
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/CLAUDE.md +26 -0
- package/README.md +8 -3
- package/package.json +1 -1
- package/src/cli/commands/firebase-init.js +1 -1
- package/src/cli/commands/logs.js +344 -0
- package/src/cli/index.js +7 -0
- package/src/manager/events/firestore/payments-webhooks/on-write.js +35 -1
- package/src/manager/routes/payments/cancel/processors/stripe.js +18 -5
- package/src/manager/routes/payments/cancel/processors/test.js +27 -14
- package/src/test/test-accounts.js +9 -0
- package/test/events/payments/journey-payments-one-time.js +3 -1
- package/test/events/payments/journey-payments-trial-cancel.js +109 -0
- package/test/events/payments/journey-payments-trial.js +12 -0
- package/test/events/payments/journey-payments-upgrade.js +3 -2
package/CLAUDE.md
CHANGED
|
@@ -447,6 +447,8 @@ When `npx bm test` starts its own emulator, logs go to `emulator.log` (since it
|
|
|
447
447
|
|
|
448
448
|
These files are overwritten on each run and are gitignored (`*.log`). Use them to search for errors, debug webhook pipelines, or review full function output after a test run.
|
|
449
449
|
|
|
450
|
+
- **`logs.log`** — Cloud Function logs from `npx bm logs:read` or `npx bm logs:tail` (raw JSON for `read`, streaming text for `tail`)
|
|
451
|
+
|
|
450
452
|
### Filtering Tests
|
|
451
453
|
```bash
|
|
452
454
|
npx bm test rules/ # Run rules tests (both BEM and project)
|
|
@@ -587,6 +589,29 @@ npx bm auth:delete <uid-or-email> # Delete user (prompts for
|
|
|
587
589
|
npx bm auth:set-claims <uid-or-email> '<json>' # Set custom claims
|
|
588
590
|
```
|
|
589
591
|
|
|
592
|
+
### Logs Commands
|
|
593
|
+
|
|
594
|
+
Fetch or stream Cloud Function logs from Google Cloud Logging. Requires `gcloud` CLI installed and authenticated. Auto-resolves the project ID from `service-account.json`, `.firebaserc`, or `GCLOUD_PROJECT`.
|
|
595
|
+
|
|
596
|
+
```bash
|
|
597
|
+
npx bm logs:read # Read last 1h of logs (default: 50 entries)
|
|
598
|
+
npx bm logs:read --fn bm_api # Filter by function name
|
|
599
|
+
npx bm logs:read --fn bm_api --severity ERROR # Filter by severity (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
|
600
|
+
npx bm logs:read --since 2d --limit 100 # Custom time range and limit
|
|
601
|
+
npx bm logs:tail # Stream live logs
|
|
602
|
+
npx bm logs:tail --fn bm_paymentsWebhookOnWrite # Stream filtered live logs
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
Both commands save output to `logs.log` in the project directory (overwritten on each run). `logs:read` saves raw JSON; `logs:tail` streams text.
|
|
606
|
+
|
|
607
|
+
| Flag | Description | Default | Commands |
|
|
608
|
+
|------|-------------|---------|----------|
|
|
609
|
+
| `--fn <name>` | Filter by Cloud Function name | all | both |
|
|
610
|
+
| `--severity <level>` | Minimum severity level | all | both |
|
|
611
|
+
| `--since <duration>` | Time range (`30m`, `1h`, `2d`, `1w`) | `1h` | read only |
|
|
612
|
+
| `--limit <n>` | Max entries | `50` | read only |
|
|
613
|
+
| `--raw` | Output raw JSON | false | both |
|
|
614
|
+
|
|
590
615
|
### Shared Flags
|
|
591
616
|
|
|
592
617
|
| Flag | Description |
|
|
@@ -985,6 +1010,7 @@ The `test` processor generates Stripe-shaped data and auto-fires webhooks to the
|
|
|
985
1010
|
| Firebase init helper (CLI) | `src/cli/commands/firebase-init.js` |
|
|
986
1011
|
| Firestore CLI commands | `src/cli/commands/firestore.js` |
|
|
987
1012
|
| Auth CLI commands | `src/cli/commands/auth.js` |
|
|
1013
|
+
| Logs CLI commands | `src/cli/commands/logs.js` |
|
|
988
1014
|
| Intent creation | `src/manager/routes/payments/intent/post.js` |
|
|
989
1015
|
| Webhook ingestion | `src/manager/routes/payments/webhook/post.js` |
|
|
990
1016
|
| Webhook processing (on-write) | `src/manager/events/firestore/payments-webhooks/on-write.js` |
|
package/README.md
CHANGED
|
@@ -749,9 +749,13 @@ npx backend-manager <command>
|
|
|
749
749
|
| `bem auth:list` | List Auth users |
|
|
750
750
|
| `bem auth:delete <uid-or-email>` | Delete an Auth user |
|
|
751
751
|
| `bem auth:set-claims <uid-or-email> '<json>'` | Set custom claims on an Auth user |
|
|
752
|
+
| `bem logs:read` | Fetch Cloud Function logs from Google Cloud Logging |
|
|
753
|
+
| `bem logs:tail` | Stream live Cloud Function logs |
|
|
752
754
|
|
|
753
755
|
All Firestore and Auth commands support `--emulator` to target the local emulator, `--force` to skip confirmation, and `--raw` for compact JSON output.
|
|
754
756
|
|
|
757
|
+
Logs commands support `--fn <name>` (function name filter), `--severity <level>`, `--since <duration>` (read only), `--limit <n>` (read only), and `--raw`. Requires `gcloud` CLI installed and authenticated.
|
|
758
|
+
|
|
755
759
|
## Environment Variables
|
|
756
760
|
|
|
757
761
|
Set these in your `functions/.env` file:
|
|
@@ -795,9 +799,10 @@ npx bm test user/ admin/ # Multiple paths
|
|
|
795
799
|
|
|
796
800
|
### Log Files
|
|
797
801
|
|
|
798
|
-
|
|
799
|
-
- **`emulator.log`** — Full emulator + Cloud Functions output
|
|
800
|
-
- **`test.log`** — Test runner output (when running against an existing emulator)
|
|
802
|
+
BEM CLI commands automatically save output to log files in the project directory:
|
|
803
|
+
- **`emulator.log`** — Full emulator + Cloud Functions output (`npx bm emulator`)
|
|
804
|
+
- **`test.log`** — Test runner output (`npx bm test`, when running against an existing emulator)
|
|
805
|
+
- **`logs.log`** — Cloud Function logs (`npx bm logs:read` or `npx bm logs:tail`)
|
|
801
806
|
|
|
802
807
|
Logs are overwritten on each run. Use them to debug failing tests or review function output.
|
|
803
808
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
const BaseCommand = require('./base-command');
|
|
2
|
+
const chalk = require('chalk');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const { execSync, spawn } = require('child_process');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const jetpack = require('fs-jetpack');
|
|
7
|
+
const { resolveProjectId } = require('./firebase-init');
|
|
8
|
+
|
|
9
|
+
const SEVERITY_COLORS = {
|
|
10
|
+
DEFAULT: 'gray',
|
|
11
|
+
DEBUG: 'gray',
|
|
12
|
+
INFO: 'cyan',
|
|
13
|
+
NOTICE: 'blue',
|
|
14
|
+
WARNING: 'yellow',
|
|
15
|
+
ERROR: 'red',
|
|
16
|
+
CRITICAL: 'redBright',
|
|
17
|
+
ALERT: 'redBright',
|
|
18
|
+
EMERGENCY: 'redBright',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
class LogsCommand extends BaseCommand {
|
|
22
|
+
async execute() {
|
|
23
|
+
const argv = this.main.argv;
|
|
24
|
+
const args = argv._ || [];
|
|
25
|
+
const subcommand = args[0]; // e.g., 'logs:read'
|
|
26
|
+
const action = subcommand.split(':')[1];
|
|
27
|
+
|
|
28
|
+
// Check gcloud is installed
|
|
29
|
+
if (!this.isGcloudInstalled()) {
|
|
30
|
+
this.logError('gcloud CLI is not installed or not in PATH.');
|
|
31
|
+
this.log(chalk.gray(' Install it: https://cloud.google.com/sdk/docs/install'));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Resolve project ID
|
|
36
|
+
const projectId = this.resolveProject();
|
|
37
|
+
if (!projectId) {
|
|
38
|
+
this.logError('Could not resolve project ID.');
|
|
39
|
+
this.log(chalk.gray(' Ensure functions/service-account.json, .firebaserc, or GCLOUD_PROJECT exists.'));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
this.log(chalk.gray(` Project: ${projectId}\n`));
|
|
44
|
+
|
|
45
|
+
switch (action) {
|
|
46
|
+
case 'read':
|
|
47
|
+
return await this.read(projectId, argv);
|
|
48
|
+
case 'tail':
|
|
49
|
+
case 'stream':
|
|
50
|
+
return await this.tail(projectId, argv);
|
|
51
|
+
default:
|
|
52
|
+
this.logError(`Unknown logs subcommand: ${action}`);
|
|
53
|
+
this.log(chalk.gray(' Available: logs:read, logs:tail, logs:stream'));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Fetch historical logs.
|
|
59
|
+
* Usage: npx bm logs:read [--fn bm_api] [--severity ERROR] [--since 1h] [--limit 50]
|
|
60
|
+
*/
|
|
61
|
+
async read(projectId, argv) {
|
|
62
|
+
const filter = this.buildFilter(argv);
|
|
63
|
+
const limit = parseInt(argv.limit, 10) || 50;
|
|
64
|
+
|
|
65
|
+
const cmd = [
|
|
66
|
+
'gcloud', 'logging', 'read',
|
|
67
|
+
filter ? `'${filter}'` : '',
|
|
68
|
+
`--project=${projectId}`,
|
|
69
|
+
`--limit=${limit}`,
|
|
70
|
+
'--format=json',
|
|
71
|
+
'--order=asc',
|
|
72
|
+
].filter(Boolean).join(' ');
|
|
73
|
+
|
|
74
|
+
// Set up log file in the project directory
|
|
75
|
+
const projectDir = this.main.firebaseProjectPath;
|
|
76
|
+
const logPath = path.join(projectDir, 'logs.log');
|
|
77
|
+
|
|
78
|
+
this.log(chalk.gray(` Filter: ${filter || '(none)'}`));
|
|
79
|
+
this.log(chalk.gray(` Limit: ${limit}`));
|
|
80
|
+
this.log(chalk.gray(` Logs saving to: ${logPath}\n`));
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
const output = execSync(cmd, {
|
|
84
|
+
encoding: 'utf8',
|
|
85
|
+
maxBuffer: 10 * 1024 * 1024, // 10MB
|
|
86
|
+
timeout: 30000,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const entries = JSON.parse(output || '[]');
|
|
90
|
+
|
|
91
|
+
// Save raw JSON to log file for Claude/tooling to read
|
|
92
|
+
jetpack.write(logPath, JSON.stringify(entries, null, 2));
|
|
93
|
+
|
|
94
|
+
if (entries.length === 0) {
|
|
95
|
+
this.logWarning('No log entries found.');
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (argv.raw) {
|
|
100
|
+
this.log(JSON.stringify(entries, null, 2));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
this.log(chalk.gray(` Found ${entries.length} entries\n`));
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
this.formatEntry(entry);
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error.status) {
|
|
110
|
+
this.logError(`gcloud command failed (exit code ${error.status}):`);
|
|
111
|
+
this.log(chalk.gray(error.stderr || error.message));
|
|
112
|
+
} else {
|
|
113
|
+
this.logError(`Failed to read logs: ${error.message}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Poll for live logs by repeatedly running gcloud logging read.
|
|
120
|
+
* Usage: npx bm logs:tail [--fn bm_api] [--severity ERROR] [--interval 5]
|
|
121
|
+
*/
|
|
122
|
+
async tail(projectId, argv) {
|
|
123
|
+
const interval = (parseInt(argv.interval, 10) || 5) * 1000;
|
|
124
|
+
let lastTimestamp = new Date(Date.now() - 60000).toISOString(); // Start 1 min ago
|
|
125
|
+
const seenIds = new Set();
|
|
126
|
+
let stopped = false;
|
|
127
|
+
|
|
128
|
+
// Set up log file in the project directory
|
|
129
|
+
const projectDir = this.main.firebaseProjectPath;
|
|
130
|
+
const logPath = path.join(projectDir, 'logs.log');
|
|
131
|
+
const logStream = fs.createWriteStream(logPath, { flags: 'w' });
|
|
132
|
+
|
|
133
|
+
const filter = this.buildFilter(argv, { excludeTimestamp: true });
|
|
134
|
+
this.log(chalk.gray(` Filter: ${filter || '(none)'}`));
|
|
135
|
+
this.log(chalk.gray(` Polling every ${interval / 1000}s`));
|
|
136
|
+
this.log(chalk.gray(` Logs saving to: ${logPath}`));
|
|
137
|
+
this.log(chalk.gray(' Tailing logs (Ctrl+C to stop)...\n'));
|
|
138
|
+
|
|
139
|
+
// Handle Ctrl+C gracefully
|
|
140
|
+
process.on('SIGINT', () => {
|
|
141
|
+
stopped = true;
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
while (!stopped) {
|
|
145
|
+
try {
|
|
146
|
+
const timestampFilter = `timestamp>="${lastTimestamp}"`;
|
|
147
|
+
const fullFilter = filter
|
|
148
|
+
? `${filter} AND ${timestampFilter}`
|
|
149
|
+
: `${timestampFilter}`;
|
|
150
|
+
|
|
151
|
+
const cmd = [
|
|
152
|
+
'gcloud', 'logging', 'read',
|
|
153
|
+
`'${fullFilter}'`,
|
|
154
|
+
`--project=${projectId}`,
|
|
155
|
+
'--limit=100',
|
|
156
|
+
'--format=json',
|
|
157
|
+
'--order=asc',
|
|
158
|
+
].join(' ');
|
|
159
|
+
|
|
160
|
+
const output = execSync(cmd, {
|
|
161
|
+
encoding: 'utf8',
|
|
162
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
163
|
+
timeout: 15000,
|
|
164
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const entries = JSON.parse(output || '[]');
|
|
168
|
+
|
|
169
|
+
for (const entry of entries) {
|
|
170
|
+
// Deduplicate using insertId
|
|
171
|
+
const entryId = entry.insertId || `${entry.timestamp}-${entry.textPayload || ''}`;
|
|
172
|
+
if (seenIds.has(entryId)) {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
seenIds.add(entryId);
|
|
176
|
+
|
|
177
|
+
// Write to log file
|
|
178
|
+
logStream.write(JSON.stringify(entry) + '\n');
|
|
179
|
+
|
|
180
|
+
// Display
|
|
181
|
+
if (argv.raw) {
|
|
182
|
+
this.log(JSON.stringify(entry));
|
|
183
|
+
} else {
|
|
184
|
+
this.formatEntry(entry);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Advance timestamp watermark
|
|
188
|
+
if (entry.timestamp && entry.timestamp > lastTimestamp) {
|
|
189
|
+
lastTimestamp = entry.timestamp;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Cap seenIds to prevent memory leak
|
|
194
|
+
if (seenIds.size > 5000) {
|
|
195
|
+
const arr = [...seenIds];
|
|
196
|
+
arr.splice(0, arr.length - 2500);
|
|
197
|
+
seenIds.clear();
|
|
198
|
+
arr.forEach(id => seenIds.add(id));
|
|
199
|
+
}
|
|
200
|
+
} catch (error) {
|
|
201
|
+
// Silently skip transient errors during polling
|
|
202
|
+
if (error.status) {
|
|
203
|
+
this.log(chalk.gray(` (poll error: ${(error.stderr || error.message).trim().split('\n')[0]})`));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Wait before next poll
|
|
208
|
+
if (!stopped) {
|
|
209
|
+
await new Promise(resolve => setTimeout(resolve, interval));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
logStream.end();
|
|
214
|
+
this.log(chalk.gray('\n Tail stopped.'));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Build a gcloud logging filter string from CLI flags.
|
|
219
|
+
*/
|
|
220
|
+
buildFilter(argv, options = {}) {
|
|
221
|
+
const parts = [];
|
|
222
|
+
|
|
223
|
+
// Always scope to Cloud Functions
|
|
224
|
+
parts.push('resource.type="cloud_function"');
|
|
225
|
+
|
|
226
|
+
// Function name filter
|
|
227
|
+
if (argv.fn) {
|
|
228
|
+
parts.push(`resource.labels.function_name="${argv.fn}"`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Severity filter
|
|
232
|
+
if (argv.severity) {
|
|
233
|
+
parts.push(`severity>=${argv.severity.toUpperCase()}`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Timestamp filter (read only, not tail)
|
|
237
|
+
if (!options.excludeTimestamp) {
|
|
238
|
+
const since = argv.since || '1h';
|
|
239
|
+
const timestamp = this.parseSince(since);
|
|
240
|
+
if (timestamp) {
|
|
241
|
+
parts.push(`timestamp>="${timestamp}"`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return parts.join(' AND ');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Parse a human-friendly duration (e.g., '1h', '2d', '30m') into an ISO timestamp.
|
|
250
|
+
*/
|
|
251
|
+
parseSince(since) {
|
|
252
|
+
const match = since.match(/^(\d+)([mhdw])$/);
|
|
253
|
+
if (!match) {
|
|
254
|
+
this.logWarning(`Invalid --since format: "${since}". Use e.g., 30m, 1h, 2d, 1w`);
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const value = parseInt(match[1], 10);
|
|
259
|
+
const unit = match[2];
|
|
260
|
+
const now = new Date();
|
|
261
|
+
|
|
262
|
+
switch (unit) {
|
|
263
|
+
case 'm': now.setMinutes(now.getMinutes() - value); break;
|
|
264
|
+
case 'h': now.setHours(now.getHours() - value); break;
|
|
265
|
+
case 'd': now.setDate(now.getDate() - value); break;
|
|
266
|
+
case 'w': now.setDate(now.getDate() - (value * 7)); break;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return now.toISOString();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Pretty-print a single log entry.
|
|
274
|
+
*/
|
|
275
|
+
formatEntry(entry) {
|
|
276
|
+
const severity = entry.severity || 'DEFAULT';
|
|
277
|
+
const colorFn = chalk[SEVERITY_COLORS[severity] || 'white'];
|
|
278
|
+
const timestamp = entry.timestamp || entry.receiveTimestamp || '';
|
|
279
|
+
const fnName = entry.resource?.labels?.function_name || '';
|
|
280
|
+
|
|
281
|
+
// Extract the actual message
|
|
282
|
+
let message = '';
|
|
283
|
+
if (entry.textPayload) {
|
|
284
|
+
message = entry.textPayload;
|
|
285
|
+
} else if (entry.jsonPayload) {
|
|
286
|
+
message = typeof entry.jsonPayload.message === 'string'
|
|
287
|
+
? entry.jsonPayload.message
|
|
288
|
+
: JSON.stringify(entry.jsonPayload, null, 2);
|
|
289
|
+
} else if (entry.protoPayload) {
|
|
290
|
+
message = JSON.stringify(entry.protoPayload, null, 2);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Format timestamp to local time
|
|
294
|
+
let timeStr = '';
|
|
295
|
+
if (timestamp) {
|
|
296
|
+
const date = new Date(timestamp);
|
|
297
|
+
timeStr = date.toLocaleTimeString();
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const severityTag = colorFn(`[${severity.padEnd(8)}]`);
|
|
301
|
+
const fnTag = fnName ? chalk.blue(`[${fnName}]`) : '';
|
|
302
|
+
const timeTag = chalk.gray(timeStr);
|
|
303
|
+
|
|
304
|
+
this.log(`${timeTag} ${severityTag} ${fnTag} ${message}`);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Resolve the project ID without initializing firebase-admin.
|
|
309
|
+
*/
|
|
310
|
+
resolveProject() {
|
|
311
|
+
const projectDir = this.firebaseProjectPath;
|
|
312
|
+
const functionsDir = path.join(projectDir, 'functions');
|
|
313
|
+
|
|
314
|
+
// Try service-account.json first (most reliable for production)
|
|
315
|
+
const serviceAccountPath = path.join(functionsDir, 'service-account.json');
|
|
316
|
+
if (jetpack.exists(serviceAccountPath)) {
|
|
317
|
+
try {
|
|
318
|
+
const sa = JSON.parse(jetpack.read(serviceAccountPath));
|
|
319
|
+
if (sa.project_id) {
|
|
320
|
+
return sa.project_id;
|
|
321
|
+
}
|
|
322
|
+
} catch (e) {
|
|
323
|
+
// Fall through
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Fall back to shared resolver
|
|
328
|
+
return resolveProjectId(projectDir, functionsDir);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Check if gcloud CLI is available.
|
|
333
|
+
*/
|
|
334
|
+
isGcloudInstalled() {
|
|
335
|
+
try {
|
|
336
|
+
execSync('gcloud --version', { encoding: 'utf8', stdio: 'pipe' });
|
|
337
|
+
return true;
|
|
338
|
+
} catch (e) {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
module.exports = LogsCommand;
|
package/src/cli/index.js
CHANGED
|
@@ -28,6 +28,7 @@ const WatchCommand = require('./commands/watch');
|
|
|
28
28
|
const StripeCommand = require('./commands/stripe');
|
|
29
29
|
const FirestoreCommand = require('./commands/firestore');
|
|
30
30
|
const AuthCommand = require('./commands/auth');
|
|
31
|
+
const LogsCommand = require('./commands/logs');
|
|
31
32
|
|
|
32
33
|
function Main() {}
|
|
33
34
|
|
|
@@ -145,6 +146,12 @@ Main.prototype.process = async function (args) {
|
|
|
145
146
|
const cmd = new AuthCommand(self);
|
|
146
147
|
return await cmd.execute();
|
|
147
148
|
}
|
|
149
|
+
|
|
150
|
+
// Logs utility commands
|
|
151
|
+
if (self.options['logs:read'] || self.options['logs:tail'] || self.options['logs:stream']) {
|
|
152
|
+
const cmd = new LogsCommand(self);
|
|
153
|
+
return await cmd.execute();
|
|
154
|
+
}
|
|
148
155
|
};
|
|
149
156
|
|
|
150
157
|
// Test method for setup command
|
|
@@ -31,6 +31,9 @@ module.exports = async ({ assistant, change, context }) => {
|
|
|
31
31
|
// Set status to processing
|
|
32
32
|
await webhookRef.set({ status: 'processing' }, { merge: true });
|
|
33
33
|
|
|
34
|
+
// Hoisted so orderId is available in catch block for audit trail
|
|
35
|
+
let orderId = null;
|
|
36
|
+
|
|
34
37
|
try {
|
|
35
38
|
const processor = dataAfter.processor;
|
|
36
39
|
const uid = dataAfter.owner;
|
|
@@ -73,7 +76,7 @@ module.exports = async ({ assistant, change, context }) => {
|
|
|
73
76
|
const webhookReceivedUNIX = dataAfter.metadata?.received?.timestampUNIX || nowUNIX;
|
|
74
77
|
|
|
75
78
|
// Extract orderId from resource (processor-agnostic)
|
|
76
|
-
|
|
79
|
+
orderId = library.getOrderId(resource);
|
|
77
80
|
|
|
78
81
|
// Process the payment event (subscription or one-time)
|
|
79
82
|
if (category !== 'subscription' && category !== 'one-time') {
|
|
@@ -100,11 +103,28 @@ module.exports = async ({ assistant, change, context }) => {
|
|
|
100
103
|
} catch (e) {
|
|
101
104
|
assistant.error(`Webhook ${eventId} failed: ${e.message}`, e);
|
|
102
105
|
|
|
106
|
+
const now = powertools.timestamp(new Date(), { output: 'string' });
|
|
107
|
+
const nowUNIX = powertools.timestamp(now, { output: 'unix' });
|
|
108
|
+
|
|
103
109
|
// Mark as failed with error message
|
|
104
110
|
await webhookRef.set({
|
|
105
111
|
status: 'failed',
|
|
106
112
|
error: e.message || String(e),
|
|
107
113
|
}, { merge: true });
|
|
114
|
+
|
|
115
|
+
// Mark intent as failed if we resolved the orderId before the error
|
|
116
|
+
if (orderId) {
|
|
117
|
+
await admin.firestore().doc(`payments-intents/${orderId}`).set({
|
|
118
|
+
status: 'failed',
|
|
119
|
+
error: e.message || String(e),
|
|
120
|
+
metadata: {
|
|
121
|
+
completed: {
|
|
122
|
+
timestamp: now,
|
|
123
|
+
timestampUNIX: nowUNIX,
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
}, { merge: true });
|
|
127
|
+
}
|
|
108
128
|
}
|
|
109
129
|
};
|
|
110
130
|
|
|
@@ -220,6 +240,20 @@ async function processPaymentEvent({ category, library, resource, resourceType,
|
|
|
220
240
|
assistant.log(`Updated payments-orders/${orderId}: type=${category}, uid=${uid}, eventType=${eventType}`);
|
|
221
241
|
}
|
|
222
242
|
|
|
243
|
+
// Update payments-intents/{orderId} status to match webhook outcome
|
|
244
|
+
if (orderId) {
|
|
245
|
+
await admin.firestore().doc(`payments-intents/${orderId}`).set({
|
|
246
|
+
status: 'completed',
|
|
247
|
+
metadata: {
|
|
248
|
+
completed: {
|
|
249
|
+
timestamp: now,
|
|
250
|
+
timestampUNIX: nowUNIX,
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
}, { merge: true });
|
|
254
|
+
assistant.log(`Updated payments-intents/${orderId}: status=completed`);
|
|
255
|
+
}
|
|
256
|
+
|
|
223
257
|
return transitionName;
|
|
224
258
|
}
|
|
225
259
|
|
|
@@ -1,22 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Stripe cancel processor
|
|
3
|
-
*
|
|
3
|
+
* Cancels a subscription — immediately if trialing, at period end otherwise.
|
|
4
4
|
*/
|
|
5
5
|
module.exports = {
|
|
6
6
|
/**
|
|
7
|
-
* Cancel a Stripe subscription
|
|
7
|
+
* Cancel a Stripe subscription
|
|
8
|
+
*
|
|
9
|
+
* If the subscription is currently trialing, cancel immediately to avoid
|
|
10
|
+
* giving free premium access for the remainder of the trial.
|
|
11
|
+
* Otherwise, cancel at the end of the current billing period.
|
|
8
12
|
*
|
|
9
13
|
* @param {object} options
|
|
10
14
|
* @param {string} options.resourceId - Stripe subscription ID (e.g., 'sub_xxx')
|
|
11
15
|
* @param {string} options.uid - User's UID (for logging)
|
|
16
|
+
* @param {object} options.subscription - User's current subscription object
|
|
12
17
|
* @param {object} options.assistant - Assistant instance for logging
|
|
13
18
|
*/
|
|
14
|
-
async cancelAtPeriodEnd({ resourceId, uid, assistant }) {
|
|
19
|
+
async cancelAtPeriodEnd({ resourceId, uid, subscription, assistant }) {
|
|
15
20
|
const StripeLib = require('../../../../libraries/payment/processors/stripe.js');
|
|
16
21
|
const stripe = StripeLib.init();
|
|
17
22
|
|
|
18
|
-
|
|
23
|
+
const isTrialing = subscription?.trial?.claimed
|
|
24
|
+
&& subscription?.status === 'active'
|
|
25
|
+
&& subscription?.trial?.expires?.timestampUNIX === subscription?.expires?.timestampUNIX;
|
|
19
26
|
|
|
20
|
-
|
|
27
|
+
if (isTrialing) {
|
|
28
|
+
await stripe.subscriptions.cancel(resourceId);
|
|
29
|
+
assistant.log(`Stripe cancel immediate (trialing): sub=${resourceId}, uid=${uid}`);
|
|
30
|
+
} else {
|
|
31
|
+
await stripe.subscriptions.update(resourceId, { cancel_at_period_end: true });
|
|
32
|
+
assistant.log(`Stripe cancel at period end: sub=${resourceId}, uid=${uid}`);
|
|
33
|
+
}
|
|
21
34
|
},
|
|
22
35
|
};
|
|
@@ -2,9 +2,13 @@ const powertools = require('node-powertools');
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Test cancel processor
|
|
5
|
-
* Simulates the Stripe webhook that results from
|
|
5
|
+
* Simulates the Stripe webhook that results from cancellation
|
|
6
6
|
* by writing directly to payments-webhooks/{eventId} with status=pending.
|
|
7
7
|
* The on-write trigger picks it up and runs the full pipeline.
|
|
8
|
+
*
|
|
9
|
+
* If the user is trialing, simulates immediate cancellation (customer.subscription.deleted).
|
|
10
|
+
* Otherwise, simulates cancel at period end (customer.subscription.updated with cancel_at_period_end=true).
|
|
11
|
+
*
|
|
8
12
|
* Only available in non-production environments.
|
|
9
13
|
*/
|
|
10
14
|
module.exports = {
|
|
@@ -16,7 +20,6 @@ module.exports = {
|
|
|
16
20
|
const admin = assistant.Manager.libraries.admin;
|
|
17
21
|
|
|
18
22
|
const timestamp = Date.now();
|
|
19
|
-
const eventId = `_test-evt-cancel-${timestamp}`;
|
|
20
23
|
const now = Math.floor(timestamp / 1000);
|
|
21
24
|
const periodEnd = now + (30 * 86400);
|
|
22
25
|
|
|
@@ -35,21 +38,31 @@ module.exports = {
|
|
|
35
38
|
}
|
|
36
39
|
}
|
|
37
40
|
|
|
38
|
-
//
|
|
39
|
-
|
|
41
|
+
// Detect if user is on a trial
|
|
42
|
+
const isTrialing = subscription?.trial?.claimed
|
|
43
|
+
&& subscription?.status === 'active'
|
|
44
|
+
&& subscription?.trial?.expires?.timestampUNIX === subscription?.expires?.timestampUNIX;
|
|
45
|
+
|
|
46
|
+
// Trialing: immediate cancel (customer.subscription.deleted)
|
|
47
|
+
// Non-trialing: cancel at period end (customer.subscription.updated)
|
|
48
|
+
const eventType = isTrialing
|
|
49
|
+
? 'customer.subscription.deleted'
|
|
50
|
+
: 'customer.subscription.updated';
|
|
51
|
+
const eventId = `_test-evt-cancel-${timestamp}`;
|
|
52
|
+
|
|
40
53
|
const subscriptionObj = {
|
|
41
54
|
id: resourceId,
|
|
42
55
|
object: 'subscription',
|
|
43
|
-
status: 'active',
|
|
56
|
+
status: isTrialing ? 'canceled' : 'active',
|
|
44
57
|
metadata: { uid, orderId },
|
|
45
|
-
cancel_at_period_end:
|
|
46
|
-
cancel_at: periodEnd,
|
|
47
|
-
canceled_at: null,
|
|
48
|
-
current_period_end: periodEnd,
|
|
58
|
+
cancel_at_period_end: !isTrialing,
|
|
59
|
+
cancel_at: isTrialing ? now : periodEnd,
|
|
60
|
+
canceled_at: isTrialing ? now : null,
|
|
61
|
+
current_period_end: isTrialing ? now : periodEnd,
|
|
49
62
|
current_period_start: now - (30 * 86400),
|
|
50
63
|
start_date: now - (30 * 86400),
|
|
51
|
-
trial_start: null,
|
|
52
|
-
trial_end: null,
|
|
64
|
+
trial_start: isTrialing ? (now - 86400) : null,
|
|
65
|
+
trial_end: isTrialing ? now : null,
|
|
53
66
|
plan: { product: stripeProductId, interval: 'month' },
|
|
54
67
|
};
|
|
55
68
|
|
|
@@ -64,11 +77,11 @@ module.exports = {
|
|
|
64
77
|
owner: uid,
|
|
65
78
|
raw: {
|
|
66
79
|
id: eventId,
|
|
67
|
-
type:
|
|
80
|
+
type: eventType,
|
|
68
81
|
data: { object: subscriptionObj },
|
|
69
82
|
},
|
|
70
83
|
event: {
|
|
71
|
-
type:
|
|
84
|
+
type: eventType,
|
|
72
85
|
category: 'subscription',
|
|
73
86
|
resourceType: 'subscription',
|
|
74
87
|
resourceId: resourceId,
|
|
@@ -86,6 +99,6 @@ module.exports = {
|
|
|
86
99
|
},
|
|
87
100
|
});
|
|
88
101
|
|
|
89
|
-
assistant.log(`Test cancel processor: wrote payments-webhooks/${eventId} for sub=${resourceId}, uid=${uid}`);
|
|
102
|
+
assistant.log(`Test cancel processor: wrote payments-webhooks/${eventId} (${eventType}) for sub=${resourceId}, uid=${uid}, trialing=${isTrialing}`);
|
|
90
103
|
},
|
|
91
104
|
};
|
|
@@ -166,6 +166,15 @@ const JOURNEY_ACCOUNTS = {
|
|
|
166
166
|
subscription: { product: { id: 'basic' }, status: 'active' }, // Starts as basic, upgraded via trial webhook
|
|
167
167
|
},
|
|
168
168
|
},
|
|
169
|
+
'journey-payments-trial-cancel': {
|
|
170
|
+
id: 'journey-payments-trial-cancel',
|
|
171
|
+
uid: '_test-journey-payments-trial-cancel',
|
|
172
|
+
email: '_test.journey-payments-trial-cancel@{domain}',
|
|
173
|
+
properties: {
|
|
174
|
+
roles: {},
|
|
175
|
+
subscription: { product: { id: 'basic' }, status: 'active' }, // Starts as basic, trial then immediate cancel
|
|
176
|
+
},
|
|
177
|
+
},
|
|
169
178
|
'journey-payments-failure': {
|
|
170
179
|
id: 'journey-payments-failure',
|
|
171
180
|
uid: '_test-journey-payments-failure',
|
|
@@ -112,7 +112,7 @@ module.exports = {
|
|
|
112
112
|
},
|
|
113
113
|
|
|
114
114
|
{
|
|
115
|
-
name: 'intent-doc-
|
|
115
|
+
name: 'intent-doc-completed',
|
|
116
116
|
async run({ firestore, assert, state }) {
|
|
117
117
|
const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
|
|
118
118
|
|
|
@@ -121,7 +121,9 @@ module.exports = {
|
|
|
121
121
|
assert.equal(intentDoc.intentId, state.intentId, 'Intent ID should match processor session ID');
|
|
122
122
|
assert.equal(intentDoc.owner, state.uid, 'Owner should match');
|
|
123
123
|
assert.equal(intentDoc.processor, 'test', 'Processor should be test');
|
|
124
|
+
assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
|
|
124
125
|
assert.equal(intentDoc.productId, state.productId, `Product should be ${state.productId}`);
|
|
126
|
+
assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
|
|
125
127
|
},
|
|
126
128
|
},
|
|
127
129
|
],
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test: Payment Journey - Trial Cancel
|
|
3
|
+
* Simulates: basic user → trial activation → cancel during trial → immediate cancellation
|
|
4
|
+
*
|
|
5
|
+
* When a user cancels during a free trial, the subscription should be cancelled immediately
|
|
6
|
+
* (not scheduled for period end) to avoid giving free premium access for the remainder of the trial.
|
|
7
|
+
*
|
|
8
|
+
* Uses the test processor for initial trial, then cancel endpoint for cancellation.
|
|
9
|
+
* Product-agnostic: resolves the first paid product from config.payment.products
|
|
10
|
+
*/
|
|
11
|
+
module.exports = {
|
|
12
|
+
description: 'Payment journey: trial → cancel during trial → immediate cancellation',
|
|
13
|
+
type: 'suite',
|
|
14
|
+
timeout: 30000,
|
|
15
|
+
|
|
16
|
+
tests: [
|
|
17
|
+
{
|
|
18
|
+
name: 'verify-starts-as-basic',
|
|
19
|
+
async run({ accounts, firestore, assert, state, config }) {
|
|
20
|
+
const uid = accounts['journey-payments-trial-cancel'].uid;
|
|
21
|
+
const userDoc = await firestore.get(`users/${uid}`);
|
|
22
|
+
|
|
23
|
+
assert.ok(userDoc, 'User doc should exist');
|
|
24
|
+
assert.equal(userDoc.subscription?.product?.id, 'basic', 'Should start as basic');
|
|
25
|
+
assert.equal(userDoc.subscription?.trial?.claimed, false, 'Trial should not be claimed');
|
|
26
|
+
|
|
27
|
+
// Resolve first paid product with trial from config
|
|
28
|
+
const trialProduct = config.payment.products.find(p => p.id !== 'basic' && p.prices && p.trial?.days);
|
|
29
|
+
assert.ok(trialProduct, 'Config should have at least one paid product with trial');
|
|
30
|
+
|
|
31
|
+
state.uid = uid;
|
|
32
|
+
state.paidProductId = trialProduct.id;
|
|
33
|
+
state.paidProductName = trialProduct.name;
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
|
|
37
|
+
{
|
|
38
|
+
name: 'create-trial-intent',
|
|
39
|
+
async run({ http, assert, state }) {
|
|
40
|
+
const response = await http.as('journey-payments-trial-cancel').post('payments/intent', {
|
|
41
|
+
processor: 'test',
|
|
42
|
+
productId: state.paidProductId,
|
|
43
|
+
frequency: 'monthly',
|
|
44
|
+
trial: true,
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
assert.isSuccess(response, 'Intent should succeed');
|
|
48
|
+
assert.ok(response.data.id, 'Should return intent ID');
|
|
49
|
+
assert.ok(response.data.orderId, 'Should return orderId');
|
|
50
|
+
|
|
51
|
+
state.intentId = response.data.id;
|
|
52
|
+
state.orderId = response.data.orderId;
|
|
53
|
+
state.eventId = response.data.id.replace('_test-cs-', '_test-evt-');
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
{
|
|
58
|
+
name: 'trial-activated',
|
|
59
|
+
async run({ firestore, assert, state, waitFor }) {
|
|
60
|
+
await waitFor(async () => {
|
|
61
|
+
const userDoc = await firestore.get(`users/${state.uid}`);
|
|
62
|
+
return userDoc?.subscription?.trial?.claimed === true;
|
|
63
|
+
}, 15000, 500);
|
|
64
|
+
|
|
65
|
+
const userDoc = await firestore.get(`users/${state.uid}`);
|
|
66
|
+
|
|
67
|
+
assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should be ${state.paidProductId}`);
|
|
68
|
+
assert.equal(userDoc.subscription.status, 'active', 'Status should be active');
|
|
69
|
+
assert.equal(userDoc.subscription.trial.claimed, true, 'Trial should be claimed');
|
|
70
|
+
assert.equal(userDoc.subscription.trial.expires.timestampUNIX, userDoc.subscription.expires.timestampUNIX, 'Trial expires should match subscription expires (still in trial period)');
|
|
71
|
+
|
|
72
|
+
state.subscriptionId = userDoc.subscription.payment.resourceId;
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
{
|
|
77
|
+
name: 'cancel-during-trial',
|
|
78
|
+
async run({ http, assert }) {
|
|
79
|
+
// Cancel via endpoint — test processor should detect trial and simulate immediate cancel
|
|
80
|
+
const response = await http.as('journey-payments-trial-cancel').post('payments/cancel', {
|
|
81
|
+
confirmed: true,
|
|
82
|
+
reason: 'Changed my mind during trial',
|
|
83
|
+
feedback: 'Testing trial cancellation',
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
assert.isSuccess(response, 'Cancel endpoint should succeed');
|
|
87
|
+
assert.equal(response.data.success, true, 'Should return { success: true }');
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
{
|
|
92
|
+
name: 'verify-immediate-cancellation',
|
|
93
|
+
async run({ firestore, assert, state, waitFor }) {
|
|
94
|
+
// Poll until subscription is cancelled (NOT just pending)
|
|
95
|
+
await waitFor(async () => {
|
|
96
|
+
const userDoc = await firestore.get(`users/${state.uid}`);
|
|
97
|
+
return userDoc?.subscription?.status === 'cancelled';
|
|
98
|
+
}, 15000, 500);
|
|
99
|
+
|
|
100
|
+
const userDoc = await firestore.get(`users/${state.uid}`);
|
|
101
|
+
|
|
102
|
+
// During trial cancel: subscription should be immediately cancelled, not pending
|
|
103
|
+
assert.equal(userDoc.subscription.status, 'cancelled', 'Status should be cancelled (not active with pending)');
|
|
104
|
+
assert.equal(userDoc.subscription.cancellation.pending, false, 'Should NOT be pending — should be fully cancelled');
|
|
105
|
+
assert.equal(userDoc.subscription.product.id, state.paidProductId, `Product should still be ${state.paidProductId}`);
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
};
|
|
@@ -79,6 +79,18 @@ module.exports = {
|
|
|
79
79
|
},
|
|
80
80
|
},
|
|
81
81
|
|
|
82
|
+
{
|
|
83
|
+
name: 'intent-doc-completed',
|
|
84
|
+
async run({ firestore, assert, state }) {
|
|
85
|
+
const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
|
|
86
|
+
|
|
87
|
+
assert.ok(intentDoc, 'Intent doc should exist');
|
|
88
|
+
assert.equal(intentDoc.id, state.orderId, 'ID should match orderId');
|
|
89
|
+
assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
|
|
90
|
+
assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
|
|
82
94
|
{
|
|
83
95
|
name: 'send-trial-to-active-webhook',
|
|
84
96
|
async run({ http, assert, state, config }) {
|
|
@@ -109,7 +109,7 @@ module.exports = {
|
|
|
109
109
|
},
|
|
110
110
|
|
|
111
111
|
{
|
|
112
|
-
name: 'intent-doc-
|
|
112
|
+
name: 'intent-doc-completed',
|
|
113
113
|
async run({ firestore, assert, state }) {
|
|
114
114
|
const intentDoc = await firestore.get(`payments-intents/${state.orderId}`);
|
|
115
115
|
|
|
@@ -118,8 +118,9 @@ module.exports = {
|
|
|
118
118
|
assert.equal(intentDoc.intentId, state.intentId, 'Intent ID should match processor session ID');
|
|
119
119
|
assert.equal(intentDoc.owner, state.uid, 'Owner should match');
|
|
120
120
|
assert.equal(intentDoc.processor, 'test', 'Processor should be test');
|
|
121
|
-
assert.equal(intentDoc.status, '
|
|
121
|
+
assert.equal(intentDoc.status, 'completed', 'Intent status should be completed after webhook processing');
|
|
122
122
|
assert.equal(intentDoc.productId, state.paidProductId, `Product should be ${state.paidProductId}`);
|
|
123
|
+
assert.ok(intentDoc.metadata?.completed?.timestampUNIX > 0, 'Completed timestamp should be set');
|
|
123
124
|
},
|
|
124
125
|
},
|
|
125
126
|
],
|