-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcli.py
More file actions
1534 lines (1237 loc) · 69.1 KB
/
cli.py
File metadata and controls
1534 lines (1237 loc) · 69.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Command Line Interface for manipulating the Session Pro Backend database like adding revocations,
flushing historical notifications received, generating reports e.t.c
"""
import argparse
import configparser
import dataclasses
import os
import pathlib
import sys
import time
import uuid
import nacl.signing
import base
import backend
import db
# Epilog definitions
BRIEF_EPILOG = """
QUICK START EXAMPLES:
server add-pro-payment --url <url> --provider <google|apple|...> [--dev-plan <1M|3M|12M>] [--dev-duration-ms ...] [--dev-auto-renewing]
server set-payment-refund-requested --url <url> --provider <google|apple> --payment-token <token> --order-id <id>
server get-pro-revocations --url <url> [--ticket <int>]
server get-pro-details --url <url> --master-skey <hex> [--count <n>]
server generate-pro-proof --url <url> --master-skey <hex> --rotating-skey <hex>
voucher --master-pkey <hex> --plan <1M|3M|12M> [--rotating-pkey <hex>] [--dev-duration-ms <ms>] (requires --config)
user-error set <provider>:<payment-id>=<true|false>[,...] (requires --config)
user-error delete <provider>:<payment-id>[,...] (requires --config)
google-notification handle <msgid>[,...] (requires --config)
google-notification delete <msgid>[,...] (requires --config)
google-notification list (requires --config)
revoke list <master_pkey_hex> (requires --config)
revoke delete <master_pkey_hex> (requires --config)
revoke timestamp [--creation-unix-ts-s <ts>] <master_pkey_hex> <unix_ts_s> (requires --config)
report generate <daily|weekly|monthly> [--format <human|csv>] [--count <n>] (requires --config)
db info (requires --config)
db print (requires --config)
"""
DETAILED_EPILOG = """
COMMAND FORMATS DETAILED:
server add-pro-payment --url <url> --provider <google|apple|...> [options]
Add a development payment to a Session Pro backend server (requires backend to be running in dev mode).
Mirrors the /add_pro_payment endpoint.
Required:
--url <url> Server URL (e.g., http://localhost:8000)
--provider Payment provider (one of the following: google, apple, rangeproof)
Optional:
--master-skey <hex> 64-char hex master secret key (generates new if omitted)
--rotating-skey <hex> 64-char hex rotating secret key (generates new if omitted)
--version <int> Request version (default: 0)
--dev-plan <1M|3M|12M> Subscription plan (1M/3M/12M)
--dev-duration-ms <ms> Override duration in milliseconds
--dev-auto-renewing Set auto-renewing to true (default: false)
The command generates DEV.-prefixed order/tx IDs and sends them to the server.
Generated keys are always printed to stdout for reproducibility.
Examples:
python cli.py server add-pro-payment --url http://localhost:8000 --provider google --dev-plan 1M
python cli.py server add-pro-payment --url http://localhost:8000 --provider apple --dev-plan 3M --master-skey abcdef...
server set-payment-refund-requested --url <url> --provider <google|apple> --master-skey <hex> [options]
Mark a development payment as refund requested. Mirrors the /set_payment_refund_requested endpoint.
Required:
--url <url> Server URL
--provider <google|apple> Payment provider
--master-skey <hex> 64-char hex master secret key
Google Required:
--payment-token <token> Google: payment token
--order-id <id> Google: order ID
Apple Required:
--tx-id <id> Apple: transaction ID
Optional:
--refund-requested-unix-ts-ms <ms> Unix timestamp ms for refund (default: now + 1s)
--version <int> Request version (default: 0)
Examples:
python cli.py server set-payment-refund-requested --url http://localhost:8000 --provider google --master-skey abcdef... --payment-token tok123 --order-id DEV.abc123
python cli.py server set-payment-refund-requested --url http://localhost:8000 --provider apple --master-skey abcdef... --tx-id DEV.xyz789
server get-pro-revocations --url <url> [--ticket <int>]
Get pro revocations from the server. Mirrors the /get_pro_revocations endpoint.
Required:
--url <url> Server URL (e.g., http://localhost:8000)
Optional:
--ticket <int> Revocation ticket to query from (default: 0)
--version <int> Request version (default: 0)
Examples:
python cli.py server get-pro-revocations --url http://localhost:8000
python cli.py server get-pro-revocations --url http://localhost:8000 --ticket 100
server get-pro-details --url <url> --master-skey <hex> [--count <n>]
Get pro details for a user. Mirrors the /get_pro_details endpoint.
Required:
--url <url> Server URL (e.g., http://localhost:8000)
--master-skey <hex> 64-char hex master secret key for signing
Optional:
--count <n> Number of payments to retrieve (default: 10)
--version <int> Request version (default: 0)
Examples:
python cli.py server get-pro-details --url http://localhost:8000 --master-skey abcdef...
python cli.py server get-pro-details --url http://localhost:8000 --master-skey abcdef... --count 5
server generate-pro-proof --url <url> --master-skey <hex> --rotating-skey <hex>
Generate a pro proof for a pre-existing subscription. Mirrors the /generate_pro_proof endpoint.
Required:
--url <url> Server URL (e.g., http://localhost:8000)
--master-skey <hex> 64-char hex master secret key for signing
--rotating-skey <hex> 64-char hex rotating secret key
Optional:
--version <int> Request version (default: 0)
Examples:
python cli.py server generate-pro-proof --url http://localhost:8000 --master-skey abcdef... --rotating-skey fedcba...
user-error set "<provider>:<payment_id>=<flag>[,...]" (requires --config)
A ',' delimited string to instruct the DB to delete the specified rows from the user errors table
in the DB on startup. This value must be of the format
"<payment_provider integer>:<payment_id>=[true|false], ..."
For example
"1:the_google_order_id=true,2:the_apple_order_id=false"
Which will add the row that has a payment provider of 1 (which corresponds to the Google Play
Store) and has a payment ID that matches "google_order_id" to have an error. For the next entry
similarly it will set the Apple row to false (e.g. delete the row from the DB)
This is intended to be used to flush errors from the DB if they are encountered during the
handling of payment notifications for a specific user. Platform clients may be using the error
table to populate UI that indicates that a user should contact support, hence clearing this
value may clear the error prompt for said user.
Examples:
python cli.py user-error set "1:abc123token=true"
python cli.py user-error set "1:token1=true,1:token2=true,2:apple1=false"
user-error set "<provider>:<payment_id>=<flag>[,...]" (requires --config)
A ',' delimited string to instruct the DB to delete the specified rows from the user errors table
in the DB on startup. This value must be of the format
"<payment_provider integer>:<payment_id>=[true|false], ..."
For example
"1:the_google_order_id=true,2:the_apple_order_id=false"
Which will add the row that has a payment provider of 1 (which corresponds to the Google Play
Store) and has a payment ID that matches "google_order_id" to have an error. For the next entry
similarly it will set the Apple row to false (e.g. delete the row from the DB)
This is intended to be used to flush errors from the DB if they are encountered during the
handling of payment notifications for a specific user. Platform clients may be using the error
table to populate UI that indicates that a user should contact support, hence clearing this
value may clear the error prompt for said user.
Options:
provider: Integer (1=Google Play Store, 2=iOS App Store)
payment_id: String (google_payment_token or apple_original_tx_id)
flag: true to add error, false to delete
Examples:
python cli.py --config config.ini user-error set "1:abc123token=true"
python cli.py --config config.ini user-error set "1:token1=true,1:token2=true,2:apple1=false"
user-error delete "<provider>:<payment_id>[,...]" (requires --config)
Same format as 'set' but only deletes (no =true/false)
Examples:
python cli.py --config config.ini user-error delete "1:abc123token"
python cli.py --config config.ini user-error delete "1:token1,1:token2,2:apple1"
voucher --config <ini> --master-pkey <hex> --plan <1M|3M|12M> [--rotating-pkey <hex>] [--dev-duration-ms <ms>] (requires --config)
Create a Rangeproof voucher payment and auto-redeem it. This is an admin command for granting
promotional or complimentary Session Pro subscriptions directly in the database.
Required:
--config <ini> Path to config.ini file
--master-pkey <hex> 64-char hex master public key of the recipient
--plan <1M|3M|12M> Subscription plan duration
Optional:
--rotating-pkey <hex> 64-char hex rotating public key (generates new if omitted)
--dev-duration-ms <ms> Override duration in milliseconds
Examples:
python cli.py voucher --config config.ini --master-pkey abcdef... --plan 1M
python cli.py voucher --config config.ini --master-pkey abcdef... --plan 3M --rotating-pkey fedcba...
python cli.py voucher --config config.ini --master-pkey abcdef... --plan 12M --dev-duration-ms 5000
google-notification handle "<message_id>[,...]" (requires --config)
A ',' delimited string of message IDs to instruct the DB to mark the specified rows as handled
from the google notification history table in the DB on startup.
"8392,1234"
Which will mark the notifications with the ID 8392 and 1234 as to being handled (which stops the
backend from trying to process the message). Note that when you handle a message, this also
wipes the notification payload from the table (since the backend does not need to parse and
process the message anymore).
Handled notifications will get deleted at the expiry date and persist in the database just incase
Google redelivers the notification. Duplicated notifications are de-duped by their message ID.
This is intended to flush out bad notifications that may be invalid or no longer necessary to
process/impossible to process due to inconsistent DB state, otherwise, do not use unless you
know the intended consequences! Make a backup of the DB before proceeding!
Options:
message_id: Google's notification message ID (an integer)
Examples:
python cli.py --config config.ini google-notification handle "12345"
python cli.py --config config.ini google-notification handle "12345,67890,11111"
google-notification delete "<message_id>[,...]" (requires --config)
Same format as 'handle', but deletes the notification entirely
google-notification list (requires --config)
Lists all unhandled notifications with message_id and expiry
revoke list <master_pkey_hex> (requires --config)
Shows all revocable payments for the user
Options:
master_pkey_hex: 64-character hex string (optionally prefixed with 0x)
Examples:
python cli.py --config config.ini revoke list aaaa...aaaa
python cli.py --config config.ini revoke list 0xaaaa...aaaa
revoke delete <master_pkey_hex> (requires --config)
Removes the revocation entry for the specified master public key
The current generation index associated with the pkey will be looked up and the corresponding
hash will be revoked. If the user is not known by the database (e.g. the user doesn't exist, or,
the user's master public key mapping has been pruned because the user was inactive for example)
then no action is taken.
revoke timestamp [--creation-unix-ts-s <ts>] <master_pkey_hex> <unix_ts_s> (requires --config)
Add or update the time (or create a new revocation entry if it doesn't exist) at which the
revocation item will be effective until.
Note that executing any revoke action increments the global generation index counter to the next
value. This is expected behaviour as a side effect of modifying the revocation table.
Options:
master_pkey_hex: 64-character hex string
unix_ts_s: Unix timestamp in seconds (not milliseconds!)
Examples:
python cli.py --config config.ini revoke timestamp --creation-unix-ts-s 1741170600 aaaa...aaaa 1741170720
report generate <period> [--format <format>] [--count <n>] (requires --config)
Generate a report of the payments for the given report type, period and optional count. The
fields of the report are defined as follows:
Active Users: Number of Session Pro payments that were still active (i.e. not expired or
revoked) at the end of the reporting period.
Cancelling: Number of Session Pro payments that are scheduled to expire and not be renewed in
that reporting period.
Options:
period: daily, weekly, or monthly
format: human (default) or csv
count: Number of periods to report (default: 7)
Examples:
python cli.py --config config.ini report generate daily
python cli.py --config config.ini report generate weekly --format csv --count 4
python cli.py --config config.ini report generate monthly --count 3
db info (requires --config)
Shows database statistics and info
db print (requires --config)
Prints all tables to stdout (for debugging)
"""
def parse_set_user_error_arg(arg: str, err: base.ErrorSink) -> list[tuple[base.PaymentProvider, str, bool]]:
"""Parse a comma-separated string of errors into a list of (payment_provider, payment_id, set_flag) tuples."""
result: list[tuple[base.PaymentProvider, str, bool]] = []
if len(arg) == 0:
return result
for item in arg.split(','):
item = item.strip()
if ':' not in item or '=' not in item:
err.msg_list.append(f"Invalid format for user error: '{item}'. Expected '<payment_provider>:<payment_id>=[true|false]'.")
return result
payment_provider_str, remainder = item.split(':', 1)
payment_id, set_flag_str = remainder.split('=', 1)
payment_provider_str = payment_provider_str.strip()
payment_provider = base.PaymentProvider.Nil
try:
payment_provider = base.PaymentProvider(int(payment_provider_str))
except Exception:
err.msg_list.append(f'Failed to parse payment provider ({payment_provider_str}) for item {item}')
return result
assert payment_provider != base.PaymentProvider.Nil, "Nil payment provider cannot be used for errors"
assert payment_provider != base.PaymentProvider.Rangeproof, "Rangeproof payment provider does not support errors"
set_flag = False
if set_flag_str.lower() == 'true':
set_flag = True
elif set_flag_str.lower() == 'false':
set_flag = False
else:
err.msg_list.append(f'Failed to parse set flag ({set_flag_str}) for item {item}')
return result
result.append((payment_provider, payment_id, set_flag))
return result
def parse_payment_id_list(arg: str, err: base.ErrorSink) -> list[tuple[base.PaymentProvider, str]]:
"""Parse a comma-separated string of payment IDs for deletion."""
result: list[tuple[base.PaymentProvider, str]] = []
if len(arg) == 0:
return result
for item in arg.split(','):
item = item.strip()
if ':' not in item:
err.msg_list.append(f"Invalid format for payment ID: '{item}'. Expected '<payment_provider>:<payment_id>'.")
return result
payment_provider_str, payment_id = item.split(':', 1)
payment_provider_str = payment_provider_str.strip()
try:
payment_provider = base.PaymentProvider(int(payment_provider_str))
except Exception:
err.msg_list.append(f'Failed to parse payment provider ({payment_provider_str}) for item {item}')
return result
result.append((payment_provider, payment_id))
return result
def parse_message_id_list(arg: str, err: base.ErrorSink) -> list[int]:
"""Parse a comma-separated string of message IDs."""
result: list[int] = []
if len(arg) == 0:
return result
for item in arg.split(','):
item = item.strip()
try:
message_id = int(item)
result.append(message_id)
except Exception:
err.msg_list.append(f'Failed to parse message_id as integer ({item})')
return result
return result
def parse_master_pkey(hex_str: str, err: base.ErrorSink) -> nacl.signing.VerifyKey | None:
"""Parse a hex string into a VerifyKey."""
if hex_str.startswith("0x"):
hex_str = hex_str[2:]
if len(hex_str) != 64:
err.msg_list.append(f"Expected 64 hex chars for master public key, received {len(hex_str)}")
return None
try:
hex_bytes = bytes.fromhex(hex_str)
return nacl.signing.VerifyKey(hex_bytes)
except Exception as e:
err.msg_list.append(f"Failed to parse hex as master public key: {e}")
return None
@dataclasses.dataclass
class CLIConfig:
db_url: str = ''
log_path: str = ''
def require_config(args: argparse.Namespace) -> CLIConfig:
if not args.config:
print("ERROR: --config is required for this command", file=sys.stderr)
sys.exit(1)
# NOTE: Parse the config
err = base.ErrorSink()
result = CLIConfig()
if 1:
config_path: str = args.config
if not pathlib.Path(config_path).exists():
err.msg_list.append(f'Config file "{config_path}" does not exist or is not readable')
return result
try:
parser = configparser.ConfigParser()
_ = parser.read(config_path)
if 'base' not in parser:
err.msg_list.append(f'Config file "{config_path}" is missing [base] section')
else:
base_section = parser['base']
result.db_url = base_section.get('db_url', '')
result.log_path = base_section.get('log_path', '')
base.DEV_BACKEND_MODE = base_section.getboolean('dev', fallback=False)
# Allow environment variable override
result.db_url = os.getenv('SESH_PRO_BACKEND_DB_URL', result.db_url)
except Exception as e:
err.msg_list.append(f'Failed to parse config file: {e}')
# NOTE: Log errors
if err.has():
msg = "ERROR: Failed to load config:\n " + "\n ".join(err.msg_list)
print(msg, file=sys.stderr)
sys.exit(1)
if not result.db_url:
print("ERROR: No database URL configured in config file", file=sys.stderr)
sys.exit(1)
return result
def load_config(config_path: str, err: base.ErrorSink) -> CLIConfig:
result = CLIConfig()
return result
def cmd_user_error_set(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
items = parse_set_user_error_arg(args.items, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if len(items) == 0:
print("No items to process")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
count = 0
label = ''
for index, (payment_provider, payment_id, set_flag) in enumerate(items):
if index:
label += '\n'
label += f' {index:02d} {payment_provider.value}:{payment_id} = {set_flag}'
if dry_run:
label += ' (dry-run)'
count += 1
continue
if set_flag:
error = backend.UserError(provider=payment_provider)
if payment_provider == base.PaymentProvider.GooglePlayStore:
error.google_payment_token = payment_id
else:
assert payment_provider == base.PaymentProvider.iOSAppStore
error.apple_original_tx_id = payment_id
if backend.has_user_error(conn=conn, payment_provider=payment_provider, payment_id=payment_id):
label += ' (skipped - already exists)'
else:
backend.add_user_error(conn=conn, error=error, unix_ts_ms=int(time.time() * 1000))
count += 1
label += ' (added)'
else:
if backend.delete_user_errors(conn=conn, payment_provider=payment_provider, payment_id=payment_id):
count += 1
label += ' (deleted)'
else:
label += ' (skipped - not found)'
print(f"Set {count}/{len(items)} user errors\n{label}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_user_error_delete(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
items = parse_payment_id_list(args.items, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if len(items) == 0:
print("No items to process")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
count = 0
label = ''
for index, (payment_provider, payment_id) in enumerate(items):
if index:
label += '\n'
label += f' {index:02d} {payment_provider.value}:{payment_id}'
if dry_run:
label += ' (dry-run)'
count += 1
continue
if backend.delete_user_errors(conn=conn, payment_provider=payment_provider, payment_id=payment_id):
count += 1
label += ' (deleted)'
else:
label += ' (skipped - not found)'
print(f"Deleted {count}/{len(items)} user errors\n{label}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_google_notification_handle(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
message_ids = parse_message_id_list(args.items, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if len(message_ids) == 0:
print("No message IDs to process")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
count = 0
label = ''
for index, message_id in enumerate(message_ids):
if index:
label += '\n'
label += f' {index:02d} {message_id} = Handled'
if dry_run:
label += ' (dry-run)'
count += 1
continue
with db.transaction(conn) as tx:
updated = backend.google_set_notification_handled(tx=tx, message_id=message_id, delete=False)
if updated:
count += 1
else:
label += ' (skipped - not found)'
print(f"Marked {count}/{len(message_ids)} google notifications as handled\n{label}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_google_notification_delete(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
message_ids = parse_message_id_list(args.items, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if len(message_ids) == 0:
print("No message IDs to process")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
count = 0
label = ''
for index, message_id in enumerate(message_ids):
if index:
label += '\n'
label += f' {index:02d} {message_id} = Delete'
if dry_run:
label += ' (dry-run)'
count += 1
continue
with db.transaction(conn) as tx:
updated = backend.google_set_notification_handled(tx=tx, message_id=message_id, delete=True)
if updated:
count += 1
else:
label += ' (skipped - not found)'
print(f"Deleted {count}/{len(message_ids)} google notifications\n{label}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_google_notification_list(args: argparse.Namespace) -> int:
config = require_config(args)
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
with db.transaction(conn) as tx:
unhandled_it = backend.google_get_unhandled_notification_iterator(tx)
items = list(unhandled_it)
if len(items) == 0:
print("No unhandled google notifications")
return 0
print(f"Found {len(items)} unhandled google notifications:")
for index, item in enumerate(items):
message_id, payload, expiry_unix_ts_ms = item
expiry_str = base.readable_unix_ts_ms(expiry_unix_ts_ms)
print(f" {index:02d} message_id={message_id}, expiry={expiry_str}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_revoke_list(args: argparse.Namespace) -> int:
config = require_config(args)
err = base.ErrorSink()
master_pkey = parse_master_pkey(args.master_pkey, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if master_pkey is None:
print("ERROR: Master public key is required", file=sys.stderr)
return 1
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
with db.transaction(conn) as tx:
user_and_payments = backend.get_user_and_payments(tx=tx, master_pkey=master_pkey)
eligible_count = 0
list_label = ''
for row in user_and_payments.payments_it:
faux_row_id = 0
payment: backend.PaymentRow = backend.payment_row_from_tuple((faux_row_id, *row))
plan_label = ''
match payment.plan:
case base.ProPlan.Nil: plan_label = '??'
case base.ProPlan.OneMonth: plan_label = '1M'
case base.ProPlan.ThreeMonth: plan_label = '3M'
case base.ProPlan.TwelveMonth: plan_label = '12M'
payment_id = ''
match payment.payment_provider:
case base.PaymentProvider.Nil: pass
case base.PaymentProvider.GooglePlayStore: payment_id = f'{payment.google_payment_token}-{payment.google_order_id}'
case base.PaymentProvider.iOSAppStore: payment_id = f'{payment.apple.original_tx_id}'
case base.PaymentProvider.Rangeproof: payment_id = f'{payment.rangeproof_order_id}'
if payment.status == base.PaymentStatus.Expired or int(time.time() * 1000) >= payment.expiry_unix_ts_ms:
continue
list_label += f'\n {eligible_count:02d} RevokeID={payment.payment_provider.name}-{payment_id}; Status={payment.status.name}; Plan={plan_label}; Unredeemed={base.readable_unix_ts_ms(payment.unredeemed_unix_ts_ms)}; Expiry={base.readable_unix_ts_ms(payment.expiry_unix_ts_ms)};'
eligible_count += 1
print(f"User {args.master_pkey} has {eligible_count} revocable payments{list_label}")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_revoke_delete(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
master_pkey = parse_master_pkey(args.master_pkey, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if master_pkey is None:
print("ERROR: Master public key is required", file=sys.stderr)
return 1
if dry_run:
print(f"(DRY RUN) Would delete revocation for {args.master_pkey}")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
with db.transaction(conn) as tx:
set_result = backend.set_revocation_tx(tx=tx, master_pkey=master_pkey, creation_unix_ts_ms=int(time.time() * 1000), expiry_unix_ts_ms=0, delete_item=True)
print(f"Deleted revocation for {args.master_pkey} ({set_result.value.lower()})")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_revoke_timestamp(args: argparse.Namespace, dry_run: bool) -> int:
config = require_config(args)
err = base.ErrorSink()
master_pkey = parse_master_pkey(args.master_pkey, err)
if err.has():
print(f"ERROR: Failed to parse arguments:\n " + "\n ".join(err.msg_list), file=sys.stderr)
return 1
if master_pkey is None:
print("ERROR: Master public key is required", file=sys.stderr)
return 1
if dry_run:
print(f"(DRY RUN) Would set revocation timestamp for {args.master_pkey} to {base.readable_unix_ts_ms(args.unix_ts_s * 1000)}")
return 0
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
with db.transaction(conn) as tx:
expiry_unix_ts_ms = args.expiry_unix_ts_s * 1000
creation_unix_ts_ms = args.creation_unix_ts_s * 1000
set_result = backend.set_revocation_tx(tx=tx, master_pkey=master_pkey, creation_unix_ts_ms=creation_unix_ts_ms, expiry_unix_ts_ms=expiry_unix_ts_ms, delete_item=False)
print(f"Set revocation for {args.master_pkey} to {base.readable_unix_ts_ms(creation_unix_ts_ms)} to {base.readable_unix_ts_ms(expiry_unix_ts_ms)} ({set_result.value.lower()})")
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_report_generate(args: argparse.Namespace) -> int:
config = require_config(args)
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
report_type = backend.ReportType.Human
if args.format.lower() == 'csv':
report_type = backend.ReportType.CSV
report_period = backend.ReportPeriod.Daily
if args.period.lower() == 'weekly':
report_period = backend.ReportPeriod.Weekly
elif args.period.lower() == 'monthly':
report_period = backend.ReportPeriod.Monthly
count = args.count
report_rows = backend.generate_report_rows(conn, report_period, limit=count)
report_str = backend.generate_report_str(report_period, report_rows, report_type)
print(report_str)
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_db_info(args: argparse.Namespace) -> int:
config = require_config(args)
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
err = base.ErrorSink()
info_str = backend.db_info_string(conn=conn, db_url=config.db_url, err=err)
if err.has():
print(f"ERROR: Failed to get DB info: {err.msg_list}", file=sys.stderr)
return 1
print(info_str)
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_db_print(args: argparse.Namespace) -> int:
config = require_config(args)
try:
with db.open_database(config.db_url) as engine:
with db.connection(engine) as conn:
base.print_db_to_stdout(conn)
return 0
except Exception as e:
print(f"ERROR: Database error: {e}", file=sys.stderr)
return 1
def cmd_server_add_pro_payment(args: argparse.Namespace) -> int:
import json
import os
import urllib.request
import urllib.error
# Parse or generate master key
if args.master_skey:
try:
master_skey = nacl.signing.SigningKey(bytes.fromhex(args.master_skey))
except Exception as e:
print(f"ERROR: Failed to parse master key: {e}", file=sys.stderr)
return 1
else:
master_skey = nacl.signing.SigningKey.generate()
print(f'Generated Master SKey: {bytes(master_skey).hex()}')
print(f'Generated Master PKey: {bytes(master_skey.verify_key).hex()}')
# Parse or generate rotating key
if args.rotating_skey:
try:
rotating_skey = nacl.signing.SigningKey(bytes.fromhex(args.rotating_skey))
except Exception as e:
print(f"ERROR: Failed to parse rotating key: {e}", file=sys.stderr)
return 1
else:
rotating_skey = nacl.signing.SigningKey.generate()
print(f'Generated Rotating SKey: {bytes(rotating_skey).hex()}')
print(f'Generated Rotating PKey: {bytes(rotating_skey.verify_key).hex()}')
# Determine provider enum and build payment_tx
if args.provider == 'google':
payment_tx_obj = backend.UserPaymentTransaction(
provider = base.PaymentProvider.GooglePlayStore,
google_payment_token = os.urandom(8).hex(),
google_order_id = 'DEV.' + os.urandom(8).hex()
)
elif args.provider == 'apple':
payment_tx_obj = backend.UserPaymentTransaction(
provider = base.PaymentProvider.iOSAppStore,
apple_tx_id = 'DEV.' + os.urandom(8).hex()
)
elif args.provider == 'rangeproof':
payment_tx_obj = backend.UserPaymentTransaction(
provider = base.PaymentProvider.Rangeproof,
rangeproof_order_id = 'DEV.' + os.urandom(8).hex()
)
else:
print(f"ERROR: Unsupported payment provider: {args.provider}", file=sys.stderr)
return 1
# Compute hash using backend function
hash_bytes = backend.make_add_pro_payment_hash(
version = args.version,
master_pkey = master_skey.verify_key,
rotating_pkey = rotating_skey.verify_key,
payment_tx = payment_tx_obj
)
# Build request
request_body = {
'version': args.version,
'master_pkey': bytes(master_skey.verify_key).hex(),
'rotating_pkey': bytes(rotating_skey.verify_key).hex(),
'master_sig': bytes(master_skey.sign(hash_bytes).signature).hex(),
'rotating_sig': bytes(rotating_skey.sign(hash_bytes).signature).hex(),
'payment_tx': {
'provider': payment_tx_obj.provider.value,
}
}
if payment_tx_obj.provider == base.PaymentProvider.GooglePlayStore:
request_body['payment_tx']['google_payment_token'] = payment_tx_obj.google_payment_token
request_body['payment_tx']['google_order_id'] = payment_tx_obj.google_order_id
elif payment_tx_obj.provider == base.PaymentProvider.iOSAppStore:
request_body['payment_tx']['apple_tx_id'] = payment_tx_obj.apple_tx_id
elif payment_tx_obj.provider == base.PaymentProvider.Rangeproof:
request_body['payment_tx']['rangeproof_order_id'] = payment_tx_obj.rangeproof_order_id
else:
print(f"ERROR: Unsupported payment provider: {args.provider}", file=sys.stderr)
return 1
# Add dev arguments
plan_map = {'1M': 'OneMonth', '3M': 'ThreeMonth', '12M': 'TwelveMonth'}
if args.dev_plan:
request_body['dev_plan'] = plan_map[args.dev_plan]
if args.dev_duration_ms is not None:
request_body['dev_duration_ms'] = args.dev_duration_ms
if args.dev_auto_renewing:
request_body['dev_auto_renewing'] = True
print(f'\nAdd Pro Payment via {"Google" if args.provider == "google" else "Apple"}')
print(f'Request:\n{json.dumps(request_body, indent=1)}')
# Send request
try:
request = urllib.request.Request(
f'{args.url}/add_pro_payment',
data=json.dumps(request_body).encode('utf-8'),
headers={"Content-Type": "application/json"},
method="POST"
)
with urllib.request.urlopen(request) as response:
response_data = json.loads(response.read().decode('utf-8'))
print(f"Response: {json.dumps(response_data, indent=1)}")
return 0
except urllib.error.HTTPError as e:
print(f"ERROR: Server returned {e.code}: {e.read().decode('utf-8')}", file=sys.stderr)
return 1
except Exception as e:
print(f"ERROR: Failed to connect to {args.url}: {e}", file=sys.stderr)
return 1
def cmd_server_set_payment_refund_requested(args: argparse.Namespace) -> int:
import json
import time
import urllib.request
import urllib.error
# Parse master key
try:
master_skey = nacl.signing.SigningKey(bytes.fromhex(args.master_skey))
except Exception as e:
print(f"ERROR: Failed to parse master key: {e}", file=sys.stderr)
return 1
# Determine provider enum and payment details
if args.provider == 'google':
provider_enum = 1
if not args.payment_token or not args.order_id:
print("ERROR: --payment-token and --order-id are required for Google", file=sys.stderr)
return 1
payment_tx = {'provider': provider_enum, 'google_payment_token': args.payment_token, 'google_order_id': args.order_id}
else: # apple
provider_enum = 2
if not args.tx_id:
print("ERROR: --tx-id is required for Apple", file=sys.stderr)
return 1
payment_tx = {'provider': provider_enum, 'apple_tx_id': args.tx_id}
# Set refund timestamp
if args.refund_requested_unix_ts_ms:
refund_unix_ts_ms = args.refund_requested_unix_ts_ms
else:
refund_unix_ts_ms = int((time.time() + 1) * 1000)
now_unix_ts_ms = int(time.time() * 1000)
# Compute hash
payment_tx = backend.UserPaymentTransaction()
if args.provider == 'google':