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