From 49a548252c449282d8788ebf5e448f5e67b2e531 Mon Sep 17 00:00:00 2001 From: Nogweii Date: Tue, 25 Jun 2024 22:58:36 -0700 Subject: [PATCH] teach `ntfy webpush` to write the keys to a file --- .gitignore | 1 + cmd/webpush.go | 23 ++++++++++++++++++++++- cmd/webpush_test.go | 7 +++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 7cbb52ac..cf10bc33 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ node_modules/ __pycache__ web/dev-dist/ venv/ +cmd/key-file.yaml diff --git a/cmd/webpush.go b/cmd/webpush.go index ec66f083..bd44f5aa 100644 --- a/cmd/webpush.go +++ b/cmd/webpush.go @@ -4,9 +4,16 @@ package cmd import ( "fmt" + "os" "github.com/SherClockHolmes/webpush-go" "github.com/urfave/cli/v2" + "github.com/urfave/cli/v2/altsrc" +) + +var flagsWebpush = append( + []cli.Flag{}, + altsrc.NewStringFlag(&cli.StringFlag{Name: "key-file", Aliases: []string{"f"}, Usage: "write vapid keys to this file"}), ) func init() { @@ -26,6 +33,7 @@ var cmdWebPush = &cli.Command{ Usage: "Generate VAPID keys to enable browser background push notifications", UsageText: "ntfy webpush keys", Category: categoryServer, + Flags: flagsWebpush, }, }, } @@ -35,7 +43,19 @@ func generateWebPushKeys(c *cli.Context) error { if err != nil { return err } - _, err = fmt.Fprintf(c.App.ErrWriter, `Web Push keys generated. Add the following lines to your config file: + + if keyFile := c.String("key-file"); keyFile != "" { + contents := fmt.Sprintf(`--- +web-push-public-key: %s +web-push-private-key: %s +`, publicKey, privateKey) + err = os.WriteFile(keyFile, []byte(contents), 0660) + if err != nil { + return err + } + _, err = fmt.Fprintf(c.App.ErrWriter, `Web Push keys written to %s.`, keyFile) + } else { + _, err = fmt.Fprintf(c.App.ErrWriter, `Web Push keys generated. Add the following lines to your config file: web-push-public-key: %s web-push-private-key: %s @@ -44,5 +64,6 @@ web-push-email-address: See https://ntfy.sh/docs/config/#web-push for details. `, publicKey, privateKey) + } return err } diff --git a/cmd/webpush_test.go b/cmd/webpush_test.go index 51926ca1..c2f19f6f 100644 --- a/cmd/webpush_test.go +++ b/cmd/webpush_test.go @@ -14,6 +14,13 @@ func TestCLI_WebPush_GenerateKeys(t *testing.T) { require.Contains(t, stderr.String(), "Web Push keys generated.") } +func TestCLI_WebPush_WriteKeysToFile(t *testing.T) { + app, _, _, stderr := newTestApp() + require.Nil(t, runWebPushCommand(app, server.NewConfig(), "keys", "--key-file=key-file.yaml")) + require.Contains(t, stderr.String(), "Web Push keys written to key-file.yaml") + require.FileExists(t, "key-file.yaml") +} + func runWebPushCommand(app *cli.App, conf *server.Config, args ...string) error { webPushArgs := []string{ "ntfy",