webpush.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "fmt"
  5. "os"
  6. "github.com/SherClockHolmes/webpush-go"
  7. "github.com/urfave/cli/v2"
  8. "github.com/urfave/cli/v2/altsrc"
  9. )
  10. var flagsWebPush = append(
  11. []cli.Flag{},
  12. altsrc.NewStringFlag(&cli.StringFlag{Name: "output-file", Aliases: []string{"f"}, Usage: "write VAPID keys to this file"}),
  13. )
  14. func init() {
  15. commands = append(commands, cmdWebPush)
  16. }
  17. var cmdWebPush = &cli.Command{
  18. Name: "webpush",
  19. Usage: "Generate keys, in the future manage web push subscriptions",
  20. UsageText: "ntfy webpush [keys]",
  21. Category: categoryServer,
  22. Subcommands: []*cli.Command{
  23. {
  24. Action: generateWebPushKeys,
  25. Name: "keys",
  26. Usage: "Generate VAPID keys to enable browser background push notifications",
  27. UsageText: "ntfy webpush keys",
  28. Category: categoryServer,
  29. Flags: flagsWebPush,
  30. },
  31. },
  32. }
  33. func generateWebPushKeys(c *cli.Context) error {
  34. privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
  35. if err != nil {
  36. return err
  37. }
  38. if outputFile := c.String("output-file"); outputFile != "" {
  39. contents := fmt.Sprintf(`---
  40. web-push-public-key: %s
  41. web-push-private-key: %s
  42. `, publicKey, privateKey)
  43. err = os.WriteFile(outputFile, []byte(contents), 0660)
  44. if err != nil {
  45. return err
  46. }
  47. _, err = fmt.Fprintf(c.App.ErrWriter, "Web Push keys written to %s.\n", outputFile)
  48. } else {
  49. _, err = fmt.Fprintf(c.App.ErrWriter, `Web Push keys generated. Add the following lines to your config file:
  50. web-push-public-key: %s
  51. web-push-private-key: %s
  52. web-push-file: /var/cache/ntfy/webpush.db # or similar
  53. web-push-email-address: <email address>
  54. See https://ntfy.sh/docs/config/#web-push for details.
  55. `, publicKey, privateKey)
  56. }
  57. return err
  58. }