key and auth flags on root command.

This commit is contained in:
fiatjaf
2026-06-11 17:49:20 -03:00
parent 7872c61a4d
commit 0c8e643609
27 changed files with 120 additions and 202 deletions
-1
View File
@@ -25,7 +25,6 @@ var admin = &cli.Command{
nak admin changerelayname myrelay.com --name "My Relay"`, nak admin changerelayname myrelay.com --name "My Relay"`,
ArgsUsage: "<relay-url>", ArgsUsage: "<relay-url>",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: defaultKeyFlags,
Commands: (func() []*cli.Command { Commands: (func() []*cli.Command {
methods := []struct { methods := []struct {
method string method string
+1 -1
View File
@@ -20,7 +20,7 @@ var blossomCmd = &cli.Command{
UseShortOptionHandling: true, UseShortOptionHandling: true,
Usage: "an army knife for blossom things", Usage: "an army knife for blossom things",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&cli.StringSliceFlag{ &cli.StringSliceFlag{
Name: "server", Name: "server",
Aliases: []string{"s"}, Aliases: []string{"s"},
+1 -1
View File
@@ -225,7 +225,7 @@ var bunker = &cli.Command{
} }
} }
} }
relays := connectToAllRelays(ctx, c, allRelays, nil) relays := connectToAllRelays(ctx, c, allRelays)
if len(relays) == 0 { if len(relays) == 0 {
log("failed to connect to any of the given relays.\n") log("failed to connect to any of the given relays.\n")
os.Exit(3) os.Exit(3)
+1 -21
View File
@@ -7,10 +7,8 @@ import (
"strings" "strings"
"fiatjaf.com/nostr" "fiatjaf.com/nostr"
"fiatjaf.com/nostr/nip42"
"fiatjaf.com/nostr/nip45" "fiatjaf.com/nostr/nip45"
"fiatjaf.com/nostr/nip45/hyperloglog" "fiatjaf.com/nostr/nip45/hyperloglog"
"github.com/fatih/color"
"github.com/mailru/easyjson" "github.com/mailru/easyjson"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
@@ -20,34 +18,16 @@ var count = &cli.Command{
Usage: "generates encoded COUNT messages and optionally use them to talk to relays", Usage: "generates encoded COUNT messages and optionally use them to talk to relays",
Description: `like 'nak req', but does a "COUNT" call instead. Will attempt to perform HyperLogLog aggregation if more than one relay is specified.`, Description: `like 'nak req', but does a "COUNT" call instead. Will attempt to perform HyperLogLog aggregation if more than one relay is specified.`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, reqFilterFlags, authFlags}), Flags: combineFlags([][]cli.Flag{reqFilterFlags}),
ArgsUsage: "[relay...]", ArgsUsage: "[relay...]",
Action: func(ctx context.Context, c *cli.Command) error { Action: func(ctx context.Context, c *cli.Command) error {
biggerUrlSize := 0 biggerUrlSize := 0
relayUrls := c.Args().Slice() relayUrls := c.Args().Slice()
if len(relayUrls) > 0 { if len(relayUrls) > 0 {
forcePreAuthSigner := authSigner
if !c.Bool("force-pre-auth") {
forcePreAuthSigner = nil
}
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error {
return authSigner(ctx, c, func(s string, args ...any) {
if strings.HasPrefix(s, "authenticating as") {
cleanUrl, _ := strings.CutPrefix(
nip42.GetRelayURLFromAuthEvent(*authEvent),
"wss://",
)
s = "authenticating to " + color.CyanString(cleanUrl) + " as" + s[len("authenticating as"):]
}
log(s+"\n", args...)
}, authEvent)
}
relays := connectToAllRelays( relays := connectToAllRelays(
ctx, ctx,
c, c,
relayUrls, relayUrls,
forcePreAuthSigner,
) )
if len(relays) == 0 { if len(relays) == 0 {
log("failed to connect to any of the given relays.\n") log("failed to connect to any of the given relays.\n")
-1
View File
@@ -19,7 +19,6 @@ var curl = &cli.Command{
Name: "curl", Name: "curl",
Usage: "calls curl but with a nip98 header", Usage: "calls curl but with a nip98 header",
Description: "accepts all flags and arguments exactly as they would be passed to curl.", Description: "accepts all flags and arguments exactly as they would be passed to curl.",
Flags: defaultKeyFlags,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Action: func(ctx context.Context, c *cli.Command) error { Action: func(ctx context.Context, c *cli.Command) error {
kr, _, err := gatherKeyerFromArguments(ctx, c) kr, _, err := gatherKeyerFromArguments(ctx, c)
+2 -2
View File
@@ -20,7 +20,7 @@ var dekey = &cli.Command{
Usage: "handles NIP-4E decoupled encryption keys", Usage: "handles NIP-4E decoupled encryption keys",
Description: "maybe this picture will explain better than I can do here for now: https://cdn.azzamo.net/89c543d261ad0d665c1dea78f91e527c2e39e7fe503b440265a3c47e63c9139f.png", Description: "maybe this picture will explain better than I can do here for now: https://cdn.azzamo.net/89c543d261ad0d665c1dea78f91e527c2e39e7fe503b440265a3c47e63c9139f.png",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&cli.StringFlag{ &cli.StringFlag{
Name: "device", Name: "device",
Usage: "name of this device that will be published and displayed on other clients", Usage: "name of this device that will be published and displayed on other clients",
@@ -87,7 +87,7 @@ var dekey = &cli.Command{
// get relays for the user // get relays for the user
log("fetching write relays for %s\n", color.CyanString(nip19.EncodeNpub(userPub))) log("fetching write relays for %s\n", color.CyanString(nip19.EncodeNpub(userPub)))
relays := sys.FetchWriteRelays(ctx, userPub) relays := sys.FetchWriteRelays(ctx, userPub)
relayList := connectToAllRelays(ctx, c, relays, nil) relayList := connectToAllRelays(ctx, c, relays)
if len(relayList) == 0 { if len(relayList) == 0 {
return fmt.Errorf("no relays to use") return fmt.Errorf("no relays to use")
} }
+4 -6
View File
@@ -13,8 +13,7 @@ var encrypt = &cli.Command{
Usage: "encrypts a string with nip44 (or nip04 if specified using a flag) and returns the resulting ciphertext as base64", Usage: "encrypts a string with nip44 (or nip04 if specified using a flag) and returns the resulting ciphertext as base64",
ArgsUsage: "[plaintext string]", ArgsUsage: "[plaintext string]",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: append( Flags: []cli.Flag{
defaultKeyFlags,
&PubKeyFlag{ &PubKeyFlag{
Name: "recipient-pubkey", Name: "recipient-pubkey",
Aliases: []string{"p", "tgt", "target", "pubkey", "to"}, Aliases: []string{"p", "tgt", "target", "pubkey", "to"},
@@ -24,7 +23,7 @@ var encrypt = &cli.Command{
Name: "nip04", Name: "nip04",
Usage: "use nip04 encryption instead of nip44", Usage: "use nip04 encryption instead of nip44",
}, },
), },
Action: func(ctx context.Context, c *cli.Command) error { Action: func(ctx context.Context, c *cli.Command) error {
target := getPubKey(c, "recipient-pubkey") target := getPubKey(c, "recipient-pubkey")
@@ -75,8 +74,7 @@ var decrypt = &cli.Command{
Usage: "decrypts a base64 nip44 ciphertext (or nip04 if specified using a flag) and returns the resulting plaintext", Usage: "decrypts a base64 nip44 ciphertext (or nip04 if specified using a flag) and returns the resulting plaintext",
ArgsUsage: "[ciphertext base64]", ArgsUsage: "[ciphertext base64]",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: append( Flags: []cli.Flag{
defaultKeyFlags,
&PubKeyFlag{ &PubKeyFlag{
Name: "sender-pubkey", Name: "sender-pubkey",
Aliases: []string{"p", "src", "source", "pubkey", "from"}, Aliases: []string{"p", "src", "source", "pubkey", "from"},
@@ -86,7 +84,7 @@ var decrypt = &cli.Command{
Name: "nip04", Name: "nip04",
Usage: "use nip04 encryption instead of nip44", Usage: "use nip04 encryption instead of nip44",
}, },
), },
Action: func(ctx context.Context, c *cli.Command) error { Action: func(ctx context.Context, c *cli.Command) error {
source := getPubKey(c, "sender-pubkey") source := getPubKey(c, "sender-pubkey")
+2 -5
View File
@@ -41,7 +41,7 @@ example:
echo '{"id":"a889df6a387419ff204305f4c2d296ee328c3cd4f8b62f205648a541b4554dfb","pubkey":"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5","created_at":1698623783,"kind":1,"tags":[],"content":"hello from the nostr army knife","sig":"84876e1ee3e726da84e5d195eb79358b2b3eaa4d9bd38456fde3e8a2af3f1cd4cda23f23fda454869975b3688797d4c66e12f4c51c1b43c6d2997c5e61865661"}' | nak event wss://offchain.pub echo '{"id":"a889df6a387419ff204305f4c2d296ee328c3cd4f8b62f205648a541b4554dfb","pubkey":"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5","created_at":1698623783,"kind":1,"tags":[],"content":"hello from the nostr army knife","sig":"84876e1ee3e726da84e5d195eb79358b2b3eaa4d9bd38456fde3e8a2af3f1cd4cda23f23fda454869975b3688797d4c66e12f4c51c1b43c6d2997c5e61865661"}' | nak event wss://offchain.pub
echo '{"tags": [["t", "spam"]]}' | nak event -c 'this is spam'`, echo '{"tags": [["t", "spam"]]}' | nak event -c 'this is spam'`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, authFlags}, Flags: combineFlags([][]cli.Flag{},
// ~ these args are only for the convoluted musig2 signing process // ~ these args are only for the convoluted musig2 signing process
// they will be generally copy-shared-pasted across some manual coordination method between participants // they will be generally copy-shared-pasted across some manual coordination method between participants
&cli.UintFlag{ &cli.UintFlag{
@@ -392,10 +392,7 @@ example:
} }
if len(relayUrls) > 0 { if len(relayUrls) > 0 {
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error { relays = connectToAllRelays(ctx, c, relayUrls)
return authSigner(ctx, c, func(s string, args ...any) {}, authEvent)
}
relays = connectToAllRelays(ctx, c, relayUrls, nil)
if len(relays) == 0 { if len(relays) == 0 {
log("failed to connect to any of the given relays.\n") log("failed to connect to any of the given relays.\n")
os.Exit(3) os.Exit(3)
+1 -17
View File
@@ -3,14 +3,11 @@ package main
import ( import (
"context" "context"
"fmt" "fmt"
"strings"
"fiatjaf.com/nostr" "fiatjaf.com/nostr"
"fiatjaf.com/nostr/nip05" "fiatjaf.com/nostr/nip05"
"fiatjaf.com/nostr/nip19" "fiatjaf.com/nostr/nip19"
"fiatjaf.com/nostr/nip42"
"fiatjaf.com/nostr/sdk/hints" "fiatjaf.com/nostr/sdk/hints"
"github.com/fatih/color"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
@@ -21,7 +18,7 @@ var fetch = &cli.Command{
nak fetch nevent1qqsxrwm0hd3s3fddh4jc2574z3xzufq6qwuyz2rvv3n087zvym3dpaqprpmhxue69uhhqatzd35kxtnjv4kxz7tfdenju6t0xpnej4 nak fetch nevent1qqsxrwm0hd3s3fddh4jc2574z3xzufq6qwuyz2rvv3n087zvym3dpaqprpmhxue69uhhqatzd35kxtnjv4kxz7tfdenju6t0xpnej4
echo npub1h8spmtw9m2huyv6v2j2qd5zv956z2zdugl6mgx02f2upffwpm3nqv0j4ps | nak fetch --relay wss://relay.nostr.band`, echo npub1h8spmtw9m2huyv6v2j2qd5zv956z2zdugl6mgx02f2upffwpm3nqv0j4ps | nak fetch --relay wss://relay.nostr.band`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, reqFilterFlags, authFlags}, Flags: combineFlags([][]cli.Flag{reqFilterFlags},
&cli.StringSliceFlag{ &cli.StringSliceFlag{
Name: "relay", Name: "relay",
Aliases: []string{"r"}, Aliases: []string{"r"},
@@ -109,19 +106,6 @@ var fetch = &cli.Command{
continue continue
} }
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error {
return authSigner(ctx, c, func(s string, args ...any) {
if strings.HasPrefix(s, "authenticating as") {
cleanUrl, _ := strings.CutPrefix(
nip42.GetRelayURLFromAuthEvent(*authEvent),
"wss://",
)
s = "authenticating to " + color.CyanString(cleanUrl) + " as" + s[len("authenticating as"):]
}
log(s+"\n", args...)
}, authEvent)
}
found := false found := false
for ie := range sys.Pool.FetchMany(ctx, relays, filter, nostr.SubscriptionOptions{ for ie := range sys.Pool.FetchMany(ctx, relays, filter, nostr.SubscriptionOptions{
Label: "nak-fetch", Label: "nak-fetch",
+1 -1
View File
@@ -24,7 +24,7 @@ var fsCmd = &cli.Command{
Usage: "mount a FUSE filesystem that exposes Nostr events as files.", Usage: "mount a FUSE filesystem that exposes Nostr events as files.",
Description: `(experimental)`, Description: `(experimental)`,
ArgsUsage: "<mountpoint>", ArgsUsage: "<mountpoint>",
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&PubKeyFlag{ &PubKeyFlag{
Name: "pubkey", Name: "pubkey",
Usage: "public key from where to to prepopulate directories", Usage: "public key from where to to prepopulate directories",
+1 -1
View File
@@ -23,7 +23,7 @@ var fsCmd = &cli.Command{
Usage: "mount a FUSE filesystem that exposes Nostr events as files.", Usage: "mount a FUSE filesystem that exposes Nostr events as files.",
Description: `(experimental)`, Description: `(experimental)`,
ArgsUsage: "<mountpoint>", ArgsUsage: "<mountpoint>",
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&PubKeyFlag{ &PubKeyFlag{
Name: "pubkey", Name: "pubkey",
Usage: "public key from where to to prepopulate directories", Usage: "public key from where to to prepopulate directories",
+1 -1
View File
@@ -22,7 +22,7 @@ var fsCmd = &cli.Command{
Usage: "mount a FUSE filesystem that exposes Nostr events as files.", Usage: "mount a FUSE filesystem that exposes Nostr events as files.",
Description: `(experimental)`, Description: `(experimental)`,
ArgsUsage: "<mountpoint>", ArgsUsage: "<mountpoint>",
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&PubKeyFlag{ &PubKeyFlag{
Name: "pubkey", Name: "pubkey",
Usage: "public key from where to to prepopulate directories", Usage: "public key from where to to prepopulate directories",
-1
View File
@@ -24,7 +24,6 @@ var gift = &cli.Command{
a decoupled key (if it has been created or received with "nak dekey" previously) will be used by default.`, a decoupled key (if it has been created or received with "nak dekey" previously) will be used by default.`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: defaultKeyFlags,
Commands: []*cli.Command{ Commands: []*cli.Command{
{ {
Name: "wrap", Name: "wrap",
-1
View File
@@ -33,7 +33,6 @@ aside from those, there is also:
- 'nak git init' for setting up nip34 repository metadata; and - 'nak git init' for setting up nip34 repository metadata; and
- 'nak git sync' for getting the latest metadata update from nostr relays (called automatically by other commands) - 'nak git sync' for getting the latest metadata update from nostr relays (called automatically by other commands)
`, `,
Flags: defaultKeyFlags,
Commands: []*cli.Command{ Commands: []*cli.Command{
{ {
Name: "init", Name: "init",
+2 -2
View File
@@ -3,7 +3,7 @@ module github.com/fiatjaf/nak
go 1.25 go 1.25
require ( require (
fiatjaf.com/nostr v0.0.0-20260603164911-395c9609550b fiatjaf.com/nostr v0.0.0-20260611201423-bd9746b22ba5
github.com/AlecAivazis/survey/v2 v2.3.7 github.com/AlecAivazis/survey/v2 v2.3.7
github.com/bep/debounce v1.2.1 github.com/bep/debounce v1.2.1
github.com/btcsuite/btcd/btcec/v2 v2.3.6 github.com/btcsuite/btcd/btcec/v2 v2.3.6
@@ -31,6 +31,7 @@ require (
fiatjaf.com/lib v0.3.7 fiatjaf.com/lib v0.3.7
github.com/hanwen/go-fuse/v2 v2.9.0 github.com/hanwen/go-fuse/v2 v2.9.0
github.com/itchyny/gojq v0.12.19 github.com/itchyny/gojq v0.12.19
github.com/lithammer/fuzzysearch v1.1.8
github.com/mattn/go-tty/v2 v2.0.0 github.com/mattn/go-tty/v2 v2.0.0
) )
@@ -77,7 +78,6 @@ require (
github.com/josharian/intern v1.0.0 // indirect github.com/josharian/intern v1.0.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/klauspost/compress v1.18.0 // indirect github.com/klauspost/compress v1.18.0 // indirect
github.com/lithammer/fuzzysearch v1.1.8 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/magefile/mage v1.14.0 // indirect github.com/magefile/mage v1.14.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
+2 -2
View File
@@ -1,7 +1,7 @@
fiatjaf.com/lib v0.3.7 h1:mXZOn7NrUcjSdy4oNvwQyAmes7Ueb+Zr5hjqMIe2dxI= fiatjaf.com/lib v0.3.7 h1:mXZOn7NrUcjSdy4oNvwQyAmes7Ueb+Zr5hjqMIe2dxI=
fiatjaf.com/lib v0.3.7/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8= fiatjaf.com/lib v0.3.7/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8=
fiatjaf.com/nostr v0.0.0-20260603164911-395c9609550b h1:uFCYH+AyyhyqL9a04BEJQ/vEZ9QP793mJWXUkIHKxWc= fiatjaf.com/nostr v0.0.0-20260611201423-bd9746b22ba5 h1:1Ten5yUsU/5DUscbkY5w1StG1+r9rdKw/xiadyjvwJU=
fiatjaf.com/nostr v0.0.0-20260603164911-395c9609550b/go.mod h1:b1EIUDnd133Ie8Pg8O/biaKdFyCMz28aD4n64g1GqvM= fiatjaf.com/nostr v0.0.0-20260611201423-bd9746b22ba5/go.mod h1:b1EIUDnd133Ie8Pg8O/biaKdFyCMz28aD4n64g1GqvM=
github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ= github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ=
github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo= github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo=
github.com/FastFilter/xorfilter v0.2.1 h1:lbdeLG9BdpquK64ZsleBS8B4xO/QW1IM0gMzF7KaBKc= github.com/FastFilter/xorfilter v0.2.1 h1:lbdeLG9BdpquK64ZsleBS8B4xO/QW1IM0gMzF7KaBKc=
+1 -14
View File
@@ -16,7 +16,6 @@ import (
"fiatjaf.com/nostr" "fiatjaf.com/nostr"
"fiatjaf.com/nostr/nip11" "fiatjaf.com/nostr/nip11"
"fiatjaf.com/nostr/nip29" "fiatjaf.com/nostr/nip29"
"fiatjaf.com/nostr/nip42"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
@@ -28,20 +27,8 @@ var group = &cli.Command{
Description: `manage and interact with Nostr communities (NIP-29). Use "nak group <subcommand> <relay>'<identifier>" where host.tld is the relay and identifier is the group identifier.`, Description: `manage and interact with Nostr communities (NIP-29). Use "nak group <subcommand> <relay>'<identifier>" where host.tld is the relay and identifier is the group identifier.`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
ArgsUsage: "<subcommand> <relay>'<identifier> [flags]", ArgsUsage: "<subcommand> <relay>'<identifier> [flags]",
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, authFlags}), Flags: combineFlags([][]cli.Flag{}),
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) { Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error {
return authSigner(ctx, c, func(s string, args ...any) {
if strings.HasPrefix(s, "authenticating as") {
cleanUrl, _ := strings.CutPrefix(
nip42.GetRelayURLFromAuthEvent(*authEvent),
"wss://",
)
s = "authenticating to " + color.CyanString(cleanUrl) + " as" + s[len("authenticating as"):]
}
log(s+"\n", args...)
}, authEvent)
}
return ctx, nil return ctx, nil
}, },
+4 -6
View File
@@ -187,7 +187,6 @@ func connectToAllRelays(
ctx context.Context, ctx context.Context,
c *cli.Command, c *cli.Command,
relayUrls []string, relayUrls []string,
preAuthSigner func(ctx context.Context, c *cli.Command, log func(s string, args ...any), authEvent *nostr.Event) (err error), // if this exists we will force preauth
) []*nostr.Relay { ) []*nostr.Relay {
// first pass to check if these are valid relay URLs // first pass to check if these are valid relay URLs
for i, url := range relayUrls { for i, url := range relayUrls {
@@ -232,7 +231,7 @@ func connectToAllRelays(
colorizepreamble(color.CyanString) colorizepreamble(color.CyanString)
go func() { go func() {
relay := connectToSingleRelay(ctx, c, url, preAuthSigner, colorizepreamble, logthis) relay := connectToSingleRelay(ctx, c, url, colorizepreamble, logthis)
if relay != nil { if relay != nil {
relays = append(relays, relay) relays = append(relays, relay)
} }
@@ -244,7 +243,7 @@ func connectToAllRelays(
// simple flow // simple flow
for _, url := range relayUrls { for _, url := range relayUrls {
log("connecting to %s... ", color.CyanString(strings.Split(url, "/")[2])) log("connecting to %s... ", color.CyanString(strings.Split(url, "/")[2]))
relay := connectToSingleRelay(ctx, c, url, preAuthSigner, nil, log) relay := connectToSingleRelay(ctx, c, url, nil, log)
if relay != nil { if relay != nil {
relays = append(relays, relay) relays = append(relays, relay)
} }
@@ -259,12 +258,11 @@ func connectToSingleRelay(
ctx context.Context, ctx context.Context,
c *cli.Command, c *cli.Command,
url string, url string,
preAuthSigner func(ctx context.Context, c *cli.Command, log func(s string, args ...any), authEvent *nostr.Event) (err error),
colorizepreamble func(c func(string, ...any) string), colorizepreamble func(c func(string, ...any) string),
logthis func(s string, args ...any), logthis func(s string, args ...any),
) *nostr.Relay { ) *nostr.Relay {
if relay, err := sys.Pool.EnsureRelay(url); err == nil { if relay, err := sys.Pool.EnsureRelay(url); err == nil {
if preAuthSigner != nil { if c.Bool("force-pre-auth") {
if colorizepreamble != nil { if colorizepreamble != nil {
colorizepreamble(color.YellowString) colorizepreamble(color.YellowString)
} }
@@ -277,7 +275,7 @@ func connectToSingleRelay(
if challengeTag == nil || len(challengeTag) < 2 || challengeTag[1] == "" { if challengeTag == nil || len(challengeTag) < 2 || challengeTag[1] == "" {
return fmt.Errorf("auth not received yet *****") // what a giant hack return fmt.Errorf("auth not received yet *****") // what a giant hack
} }
return preAuthSigner(ctx, c, logthis, authEvent) return authSigner(ctx, c, logthis, authEvent)
}); err == nil { }); err == nil {
// auth succeeded // auth succeeded
goto preauthSuccess goto preauthSuccess
+2 -41
View File
@@ -18,46 +18,6 @@ import (
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
var defaultKey = nostr.KeyOne.Hex()
var authFlags = []cli.Flag{
&cli.BoolFlag{
Name: "auth",
Usage: "always perform nip42 \"AUTH\" when facing an \"auth-required: \" rejection and try again",
Category: CATEGORY_AUTH,
},
&cli.BoolFlag{
Name: "force-pre-auth",
Aliases: []string{"fpa"},
Usage: "after connecting, wait for a nip42 \"AUTH\" message to be received, act on it and only then send the query",
Category: CATEGORY_AUTH,
},
}
var defaultKeyFlags = []cli.Flag{
&cli.StringFlag{
Name: "sec",
Usage: "secret key to sign the event, as nsec, ncryptsec or hex, or a bunker URL",
DefaultText: "the key '01'",
Category: CATEGORY_SIGNER,
Sources: cli.EnvVars("NOSTR_SECRET_KEY"),
Value: defaultKey,
HideDefault: true,
},
&cli.BoolFlag{
Name: "prompt-sec",
Usage: "prompt the user to paste a hex or nsec with which to sign the event",
Category: CATEGORY_SIGNER,
},
&cli.StringFlag{
Name: "connect-as",
Usage: "private key to use when communicating with nip46 bunkers",
DefaultText: "a random key",
Category: CATEGORY_SIGNER,
Sources: cli.EnvVars("NOSTR_CLIENT_KEY"),
},
}
func gatherKeyerFromArguments(ctx context.Context, c *cli.Command) (nostr.Keyer, nostr.SecretKey, error) { func gatherKeyerFromArguments(ctx context.Context, c *cli.Command) (nostr.Keyer, nostr.SecretKey, error) {
key, bunker, err := gatherSecretKeyOrBunkerFromArguments(ctx, c) key, bunker, err := gatherSecretKeyOrBunkerFromArguments(ctx, c)
if err != nil { if err != nil {
@@ -136,13 +96,14 @@ func authSigner(ctx context.Context, c *cli.Command, log func(s string, args ...
defer func() { defer func() {
if err != nil { if err != nil {
cleanUrl, _ := strings.CutPrefix(nip42.GetRelayURLFromAuthEvent(*authEvent), "wss://") cleanUrl, _ := strings.CutPrefix(nip42.GetRelayURLFromAuthEvent(*authEvent), "wss://")
log("%s auth failed: %s", colors.errorf(cleanUrl), err) log("%s auth failed: %s\n", colors.errorf(cleanUrl), err)
} }
}() }()
if !c.Bool("auth") && !c.Bool("force-pre-auth") { if !c.Bool("auth") && !c.Bool("force-pre-auth") {
return fmt.Errorf("auth required, but --auth flag not given") return fmt.Errorf("auth required, but --auth flag not given")
} }
kr, _, err := gatherKeyerFromArguments(ctx, c) kr, _, err := gatherKeyerFromArguments(ctx, c)
if err != nil { if err != nil {
return err return err
+85 -38
View File
@@ -13,6 +13,46 @@ import (
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
var defaultKey = nostr.KeyOne.Hex()
var authFlags = []cli.Flag{
&cli.BoolFlag{
Name: "auth",
Usage: "always perform nip42 \"AUTH\" when facing an \"auth-required: \" rejection and try again",
Category: CATEGORY_AUTH,
},
&cli.BoolFlag{
Name: "force-pre-auth",
Aliases: []string{"fpa"},
Usage: "after connecting, wait for a nip42 \"AUTH\" message to be received, act on it and only then send the query",
Category: CATEGORY_AUTH,
},
}
var defaultKeyFlags = []cli.Flag{
&cli.StringFlag{
Name: "sec",
Usage: "secret key to sign the event, as nsec, ncryptsec or hex, or a bunker URL",
DefaultText: "the key '01'",
Category: CATEGORY_SIGNER,
Sources: cli.EnvVars("NOSTR_SECRET_KEY"),
Value: defaultKey,
HideDefault: true,
},
&cli.BoolFlag{
Name: "prompt-sec",
Usage: "prompt the user to paste a hex or nsec with which to sign the event",
Category: CATEGORY_SIGNER,
},
&cli.StringFlag{
Name: "connect-as",
Usage: "private key to use when communicating with nip46 bunkers",
DefaultText: "a random key",
Category: CATEGORY_SIGNER,
Sources: cli.EnvVars("NOSTR_CLIENT_KEY"),
},
}
var ( var (
version string = "debug" version string = "debug"
isVerbose bool = false isVerbose bool = false
@@ -61,47 +101,51 @@ var app = &cli.Command{
validateCmd, validateCmd,
}, },
Version: version, Version: version,
Flags: []cli.Flag{ Flags: combineFlags([][]cli.Flag{
&cli.StringFlag{ {
Name: "config-path", &cli.StringFlag{
Hidden: true, Name: "config-path",
Value: (func() string { Hidden: true,
if home, err := os.UserHomeDir(); err == nil { Value: (func() string {
return filepath.Join(home, ".config/nak") if home, err := os.UserHomeDir(); err == nil {
} else { return filepath.Join(home, ".config/nak")
return "" } else {
} return ""
})(),
},
&cli.BoolFlag{
Name: "quiet",
Usage: "do not print logs and info messages to stderr, use -qq to also not print anything to stdout",
Aliases: []string{"q"},
Action: func(ctx context.Context, c *cli.Command, b bool) error {
q := c.Count("quiet")
if q >= 1 {
log = func(msg string, args ...any) {}
if q >= 2 {
stdout = func(_ ...any) {}
} }
} })(),
return nil },
&cli.BoolFlag{
Name: "quiet",
Usage: "do not print logs and info messages to stderr, use -qq to also not print anything to stdout",
Aliases: []string{"q"},
Action: func(ctx context.Context, c *cli.Command, b bool) error {
q := c.Count("quiet")
if q >= 1 {
log = func(msg string, args ...any) {}
if q >= 2 {
stdout = func(_ ...any) {}
}
}
return nil
},
},
&cli.BoolFlag{
Name: "verbose",
Usage: "print more stuff than normally",
Aliases: []string{"v"},
Action: func(ctx context.Context, c *cli.Command, b bool) error {
v := c.Count("verbose")
if v >= 1 {
logverbose = log
isVerbose = true
}
return nil
},
}, },
}, },
&cli.BoolFlag{ defaultKeyFlags,
Name: "verbose", authFlags,
Usage: "print more stuff than normally", }),
Aliases: []string{"v"},
Action: func(ctx context.Context, c *cli.Command, b bool) error {
v := c.Count("verbose")
if v >= 1 {
logverbose = log
isVerbose = true
}
return nil
},
},
},
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) { Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
sys = sdk.NewSystem() sys = sdk.NewSystem()
@@ -112,6 +156,9 @@ var app = &cli.Command{
sys.Pool.RelayOptions = nostr.RelayOptions{ sys.Pool.RelayOptions = nostr.RelayOptions{
RequestHeader: http.Header{textproto.CanonicalMIMEHeaderKey("user-agent"): {"nak/b"}}, RequestHeader: http.Header{textproto.CanonicalMIMEHeaderKey("user-agent"): {"nak/b"}},
} }
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error {
return authSigner(ctx, c, log, authEvent)
}
return ctx, nil return ctx, nil
}, },
+1 -3
View File
@@ -19,9 +19,7 @@ var mcpServer = &cli.Command{
Usage: "pander to the AI gods", Usage: "pander to the AI gods",
Description: ``, Description: ``,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: append( Flags: []cli.Flag{},
defaultKeyFlags,
),
Action: func(ctx context.Context, c *cli.Command) error { Action: func(ctx context.Context, c *cli.Command) error {
s := server.NewMCPServer( s := server.NewMCPServer(
"nak", "nak",
+1 -1
View File
@@ -5,9 +5,9 @@ import (
"sync/atomic" "sync/atomic"
"syscall" "syscall"
"fiatjaf.com/nostr"
"github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fs"
"github.com/hanwen/go-fuse/v2/fuse" "github.com/hanwen/go-fuse/v2/fuse"
"fiatjaf.com/nostr"
) )
type AsyncFile struct { type AsyncFile struct {
+2 -5
View File
@@ -23,7 +23,7 @@ var nsite = &cli.Command{
Usage: "publishes and downloads nip-5A static sites", Usage: "publishes and downloads nip-5A static sites",
ArgsUsage: "<directory> [relay...]", ArgsUsage: "<directory> [relay...]",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, authFlags}), Flags: combineFlags([][]cli.Flag{}),
Commands: []*cli.Command{ Commands: []*cli.Command{
{ {
Name: "upload", Name: "upload",
@@ -215,10 +215,7 @@ var nsite = &cli.Command{
return fmt.Errorf("no relays to publish this nsite to") return fmt.Errorf("no relays to publish this nsite to")
} }
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error { relays := connectToAllRelays(ctx, c, relayURLs)
return authSigner(ctx, c, func(string, ...any) {}, authEvent)
}
relays := connectToAllRelays(ctx, c, relayURLs, nil)
if len(relays) == 0 { if len(relays) == 0 {
return fmt.Errorf("failed to connect to any of [ %v ]", relayURLs) return fmt.Errorf("failed to connect to any of [ %v ]", relayURLs)
} }
+2 -5
View File
@@ -23,7 +23,7 @@ example:
echo "I agree!" | nak publish --reply nevent1... echo "I agree!" | nak publish --reply nevent1...
echo "tagged post" | nak publish -t t=mytag -t e=someeventid`, echo "tagged post" | nak publish -t t=mytag -t e=someeventid`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, authFlags}, Flags: combineFlags([][]cli.Flag{},
&cli.StringFlag{ &cli.StringFlag{
Name: "reply", Name: "reply",
Usage: "event id, naddr1 or nevent1 code to reply to", Usage: "event id, naddr1 or nevent1 code to reply to",
@@ -150,10 +150,7 @@ example:
relayUrls = nostr.AppendUnique(relayUrls, replyRelays...) relayUrls = nostr.AppendUnique(relayUrls, replyRelays...)
relayUrls = nostr.AppendUnique(relayUrls, c.Args().Slice()...) relayUrls = nostr.AppendUnique(relayUrls, c.Args().Slice()...)
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error { relays := connectToAllRelays(ctx, c, relayUrls)
return authSigner(ctx, c, func(s string, args ...any) {}, authEvent)
}
relays := connectToAllRelays(ctx, c, relayUrls, nil)
if len(relays) == 0 { if len(relays) == 0 {
if len(relayUrls) == 0 { if len(relayUrls) == 0 {
+1 -23
View File
@@ -15,10 +15,8 @@ import (
"fiatjaf.com/nostr/eventstore" "fiatjaf.com/nostr/eventstore"
"fiatjaf.com/nostr/eventstore/slicestore" "fiatjaf.com/nostr/eventstore/slicestore"
"fiatjaf.com/nostr/eventstore/wrappers" "fiatjaf.com/nostr/eventstore/wrappers"
"fiatjaf.com/nostr/nip42"
"fiatjaf.com/nostr/nip77" "fiatjaf.com/nostr/nip77"
"fiatjaf.com/nostr/schema" "fiatjaf.com/nostr/schema"
"github.com/fatih/color"
"github.com/mailru/easyjson" "github.com/mailru/easyjson"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
@@ -43,7 +41,7 @@ it can also take a filter from stdin, optionally modify it with flags and send i
example: example:
echo '{"kinds": [1], "#t": ["test"]}' | nak req -l 5 -k 4549 --tag t=spam wss://nostr-pub.wellorder.net`, echo '{"kinds": [1], "#t": ["test"]}' | nak req -l 5 -k 4549 --tag t=spam wss://nostr-pub.wellorder.net`,
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags, reqFilterFlags, authFlags}, Flags: combineFlags([][]cli.Flag{reqFilterFlags},
&cli.StringFlag{ &cli.StringFlag{
Name: "jq", Name: "jq",
Usage: "filter returned events with jq expression", Usage: "filter returned events with jq expression",
@@ -135,30 +133,10 @@ example:
} }
if len(relayUrls) > 0 && !negentropy { if len(relayUrls) > 0 && !negentropy {
// this is used both for the normal AUTH (after "auth-required:" is received) or forced pre-auth
// connect to all relays we expect to use in this call in parallel
forcePreAuthSigner := authSigner
if !c.Bool("force-pre-auth") {
forcePreAuthSigner = nil
}
sys.Pool.AuthRequiredHandler = func(ctx context.Context, authEvent *nostr.Event) error {
return authSigner(ctx, c, func(s string, args ...any) {
if strings.HasPrefix(s, "authenticating as") {
cleanUrl, _ := strings.CutPrefix(
nip42.GetRelayURLFromAuthEvent(*authEvent),
"wss://",
)
s = "authenticating to " + color.CyanString(cleanUrl) + " as" + s[len("authenticating as"):]
}
log(s+"\n", args...)
}, authEvent)
}
relays := connectToAllRelays( relays := connectToAllRelays(
ctx, ctx,
c, c,
relayUrls, relayUrls,
forcePreAuthSigner,
) )
// stop here already if all connections failed // stop here already if all connections failed
+1 -1
View File
@@ -23,7 +23,7 @@ var spell = &cli.Command{
Usage: "downloads a spell event and executes its REQ request", Usage: "downloads a spell event and executes its REQ request",
ArgsUsage: "[nevent_code]", ArgsUsage: "[nevent_code]",
Description: `fetches a spell event (kind 777) and executes REQ command encoded in its tags.`, Description: `fetches a spell event (kind 777) and executes REQ command encoded in its tags.`,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&cli.StringFlag{ &cli.StringFlag{
Name: "pub", Name: "pub",
Usage: "public key to run spells in the context of (if you don't want to pass a --sec)", Usage: "public key to run spells in the context of (if you don't want to pass a --sec)",
+1 -1
View File
@@ -105,7 +105,7 @@ var wallet = &cli.Command{
Usage: "displays the current wallet balance", Usage: "displays the current wallet balance",
Description: "all wallet data is stored on Nostr relays, signed and encrypted with the given key, and reloaded again from relays on every call.\n\nthe same data can be accessed by other compatible nip60 clients.", Description: "all wallet data is stored on Nostr relays, signed and encrypted with the given key, and reloaded again from relays on every call.\n\nthe same data can be accessed by other compatible nip60 clients.",
DisableSliceFlagSeparator: true, DisableSliceFlagSeparator: true,
Flags: combineFlags([][]cli.Flag{defaultKeyFlags}, Flags: combineFlags([][]cli.Flag{},
&cli.BoolFlag{ &cli.BoolFlag{
Name: "stream", Name: "stream",
Usage: "keep listening for wallet-related events and logging them", Usage: "keep listening for wallet-related events and logging them",