diff --git a/docs/n8n_community-package.md b/docs/n8n_community-package.md index 6c35594..c267ac3 100644 --- a/docs/n8n_community-package.md +++ b/docs/n8n_community-package.md @@ -24,6 +24,7 @@ n8n community-package [flags] ``` n8n community-package list n8n community-package install n8n-nodes-example + n8n community-package install '@scope/n8n-nodes-example' --yes n8n community-package update n8n-nodes-example --yes n8n community-package uninstall n8n-nodes-example --yes ``` diff --git a/docs/n8n_community-package_install.md b/docs/n8n_community-package_install.md index 3a175bc..d517429 100644 --- a/docs/n8n_community-package_install.md +++ b/docs/n8n_community-package_install.md @@ -6,10 +6,11 @@ Install a community package Install an npm community node package on the selected n8n instance. -The package name must start with n8n-nodes-. Omit --version to let npm select -the version. Verification against n8n's vetted package list is enabled by -default; --verify=false explicitly permits unverified code when the instance -allows it. Installed package code runs inside n8n. +The package name must have the form n8n-nodes- or the scoped form +@/n8n-nodes-. --version takes a semver version or an npm dist-tag +such as latest or beta; omit it to let npm select the version. Whether +unverified packages may be installed is an instance setting: when it is off, +only versions verified by n8n install. Installed package code runs inside n8n. Interactive runs ask before installing. Non-interactive runs fail unless --yes is passed. Requires API-key authentication and communityPackage:install. @@ -24,7 +25,7 @@ n8n community-package install [flags] ``` n8n community-package install n8n-nodes-example n8n community-package install n8n-nodes-example --version 1.2.3 --yes - n8n community-package install n8n-nodes-example --verify=false --yes --output json + n8n community-package install '@scope/n8n-nodes-example' --version beta --yes --output json ``` ### Options @@ -34,8 +35,7 @@ n8n community-package install [flags] -h, --help help for install --output string output format: text or json (default text; json is stable for scripting) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --verify verify against n8n's vetted package list (default true; --verify=false permits unverified code when allowed) (default true) - --version string npm package version, e.g. 1.2.3 (default: let n8n select the version) + --version string npm semver version or dist-tag, e.g. 1.2.3 or beta (default: let n8n select the version) --yes confirm the instance-changing action without prompting (required when stdin is not interactive) ``` diff --git a/docs/n8n_community-package_update.md b/docs/n8n_community-package_update.md index 54d5be1..dcc3a8d 100644 --- a/docs/n8n_community-package_update.md +++ b/docs/n8n_community-package_update.md @@ -6,10 +6,11 @@ Update an installed community package Update one installed community node package on the selected n8n instance. -Omit --version to update to the version selected by n8n. Verification against -n8n's vetted package list is enabled by default; --verify=false explicitly -permits unverified code when the instance allows it. Updating code can change -node behavior in existing workflows, though it does not delete those workflows. +--version takes a semver version or an npm dist-tag such as latest or beta. +Omit it to send no body and update to the latest version n8n allows. Whether +unverified versions may be installed is an instance setting: when it is off, +only versions verified by n8n install. Updating code can change node behavior +in existing workflows, though it does not delete those workflows. Interactive runs ask before updating. Non-interactive runs fail unless --yes is passed. Requires API-key authentication and communityPackage:update. @@ -34,8 +35,7 @@ n8n community-package update [flags] -h, --help help for update --output string output format: text or json (default text; json is stable for scripting) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --verify verify against n8n's vetted package list (default true; --verify=false permits unverified code when allowed) (default true) - --version string npm package version, e.g. 1.2.3 (default: let n8n select the version) + --version string npm semver version or dist-tag, e.g. 1.2.3 or beta (default: let n8n select the version) --yes confirm the instance-changing action without prompting (required when stdin is not interactive) ``` diff --git a/docs/n8n_user.md b/docs/n8n_user.md index d7d5b10..b21c87b 100644 --- a/docs/n8n_user.md +++ b/docs/n8n_user.md @@ -11,7 +11,8 @@ access. Create accepts a strict JSON array and preserves every per-user success or error. Role changes and deletion accept the exact user ID or email allowed by -the API. Deletion always requires confirmation. +the API. Deletion always requires confirmation and deletes the user's workflows +and credentials unless --transfer-to-project moves them to a project. ``` n8n user [flags] @@ -24,7 +25,7 @@ n8n user [flags] n8n user get person@example.com --include-role n8n user create --input users.json n8n user role set USER_ID global:member - n8n user delete USER_ID --yes + n8n user delete USER_ID --transfer-to-project PROJECT_ID --yes ``` ### Options diff --git a/docs/n8n_user_create.md b/docs/n8n_user_create.md index 9f1d32f..99dcebf 100644 --- a/docs/n8n_user_create.md +++ b/docs/n8n_user_create.md @@ -5,7 +5,8 @@ Invite one or more users ### Synopsis Create or invite users from a strict JSON array supplied by --input. Each item -requires email and may set a global role slug. Unknown fields, an empty array, +requires email and may set role: global:admin, global:member (the default), +global:chatUser, or a custom global role slug. Unknown fields, an empty array, invalid emails, and trailing JSON documents are refused before transport. n8n returns one result per invitation. Output preserves successful users, invite diff --git a/docs/n8n_user_delete.md b/docs/n8n_user_delete.md index a7de229..8da8076 100644 --- a/docs/n8n_user_delete.md +++ b/docs/n8n_user_delete.md @@ -5,11 +5,14 @@ Permanently delete a user ### Synopsis Permanently delete one user using the exact ID or email accepted by the API. -This removes the account and can delete resources owned by its personal project; -the documented endpoint provides no ownership-transfer option. It cannot be -undone and the instance owner cannot be deleted. - -Interactive runs ask for confirmation. Non-interactive runs require --yes. +By default n8n also deletes the user's workflows and credentials. Pass +--transfer-to-project with a project ID (sent as the API's transferId) to move +those workflows and credentials to that project instead; find IDs with +'n8n project list'. Deletion cannot be undone and the instance owner cannot be +deleted. + +Interactive runs ask for confirmation naming what happens to the user's +workflows and credentials. Non-interactive runs require --yes. Requires user:delete. ``` @@ -19,18 +22,19 @@ n8n user delete [flags] ### Examples ``` - n8n user delete USER_ID + n8n user delete USER_ID --transfer-to-project PROJECT_ID n8n user delete person@example.com --yes --output json ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for delete - --output string output format: text or json (acknowledgement contains only deleted user identifier) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --yes confirm permanent user and owned-resource deletion without prompting (required when stdin is not interactive) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for delete + --output string output format: text or json (acknowledgement contains deleted user identifier and any transfer project ID) (default "text") + --transfer-to-project string project ID that receives the user's workflows and credentials (default: none, they are deleted with the user) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm permanent user deletion, and deletion of their workflows and credentials unless transferred, without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_user_list.md b/docs/n8n_user_list.md index fce77cc..f5e26ff 100644 --- a/docs/n8n_user_list.md +++ b/docs/n8n_user_list.md @@ -6,8 +6,7 @@ List instance or project users List users visible to the selected credential. Use --project-id to filter to one project's members and --include-role to request global roles. The API is -cursor-paginated; --offset selects a starting position, while --cursor resumes -a previous response. They cannot be combined. +cursor-paginated: --cursor resumes from the nextCursor of a previous response. --all follows cursors and collects at most 10,000 users. Instance-wide listing may require the instance owner. Requires user:list. @@ -28,7 +27,7 @@ n8n user list [flags] ``` n8n user list --include-role n8n user list --project-id PROJECT_ID --limit 50 - n8n user list --offset 100 --output json + n8n user list --cursor NEXT_CURSOR --output json n8n user list --all --include-role --output json ``` @@ -37,11 +36,10 @@ n8n user list [flags] ``` --all follow every page instead of one (maximum 10,000 users; hitting it warns and sets JSON collection.truncated) --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --cursor string pagination cursor returned by a previous list (default: first page; cannot combine with --offset) + --cursor string pagination cursor returned by a previous list (default: first page) -h, --help help for list --include-role include each user's global role (default: role is omitted by API) --limit int users per API page, 1 to 250 (default: server default of 100) - --offset int users to skip before first page, zero or greater (default: 0; cannot combine with --cursor) --output string output format: text or json (JSON is a paginated user object, plus collection with --all) (default "text") --project-id string return members of this project ID (default: all visible instance users) --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) diff --git a/docs/n8n_user_role.md b/docs/n8n_user_role.md index 32c4c74..c0e9328 100644 --- a/docs/n8n_user_role.md +++ b/docs/n8n_user_role.md @@ -5,8 +5,9 @@ Manage users' global roles ### Synopsis Manage global role assignments for instance users. Use 'set' with a user ID -or email and a role slug discovered through 'n8n role list'. Role changes can -alter instance-wide permissions and may require owner access or licensing. +or email and a role slug: global:admin, global:member, global:chatUser, or a +custom global role discovered through 'n8n role list'. Role changes can alter +instance-wide permissions and may require owner access or licensing. ``` n8n user role [flags] @@ -16,7 +17,7 @@ n8n user role [flags] ``` n8n user role set USER_ID global:member - n8n user role set person@example.com global:admin --output json + n8n user role set person@example.com global:chatUser --output json ``` ### Options diff --git a/docs/n8n_user_role_set.md b/docs/n8n_user_role_set.md index 21192e9..43c6ebb 100644 --- a/docs/n8n_user_role_set.md +++ b/docs/n8n_user_role_set.md @@ -5,9 +5,10 @@ Set a user's global role ### Synopsis Change one user's global role using the exact user ID or email accepted by the -API. The role slug must identify an assignable global role; run 'n8n role list' -to inspect licensing and available slugs. This can immediately change the user's -instance permissions. Requires user:changeRole. +API. The role slug must identify an assignable global role: global:admin, +global:member, global:chatUser, or a custom global role slug. Run 'n8n role +list' to inspect licensing and available slugs. This can immediately change the +user's instance permissions. Requires user:changeRole. ``` n8n user role set [flags] @@ -17,7 +18,8 @@ n8n user role set [flags] ``` n8n user role set USER_ID global:member - n8n user role set person@example.com global:admin --output json + n8n user role set person@example.com global:chatUser + n8n user role set USER_ID CUSTOM_ROLE_SLUG --output json ``` ### Options diff --git a/internal/cli/community_package.go b/internal/cli/community_package.go index bef9789..854c618 100644 --- a/internal/cli/community_package.go +++ b/internal/cli/community_package.go @@ -28,6 +28,7 @@ func newCommunityPackageCommand(opts Options) *cobra.Command { "installed packages, then install, update or uninstall one package.", Example: " n8n community-package list\n" + " n8n community-package install n8n-nodes-example\n" + + " n8n community-package install '@scope/n8n-nodes-example' --yes\n" + " n8n community-package update n8n-nodes-example --yes\n" + " n8n community-package uninstall n8n-nodes-example --yes", Args: cobra.NoArgs, @@ -133,22 +134,23 @@ func newCommunityPackageInstallCommand(opts Options) *cobra.Command { Use: "install ", Short: "Install a community package", Long: "Install an npm community node package on the selected n8n instance.\n\n" + - "The package name must start with n8n-nodes-. Omit --version to let npm select\n" + - "the version. Verification against n8n's vetted package list is enabled by\n" + - "default; --verify=false explicitly permits unverified code when the instance\n" + - "allows it. Installed package code runs inside n8n.\n\n" + + "The package name must have the form n8n-nodes- or the scoped form\n" + + "@/n8n-nodes-. --version takes a semver version or an npm dist-tag\n" + + "such as latest or beta; omit it to let npm select the version. Whether\n" + + "unverified packages may be installed is an instance setting: when it is off,\n" + + "only versions verified by n8n install. Installed package code runs inside n8n.\n\n" + "Interactive runs ask before installing. Non-interactive runs fail unless --yes\n" + "is passed. Requires API-key authentication and communityPackage:install.\n" + "Next step: 'n8n community-package list'.", Example: " n8n community-package install n8n-nodes-example\n" + " n8n community-package install n8n-nodes-example --version 1.2.3 --yes\n" + - " n8n community-package install n8n-nodes-example --verify=false --yes --output json", + " n8n community-package install '@scope/n8n-nodes-example' --version beta --yes --output json", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runCommunityPackageInstall(cmd.Context(), opts, args[0], f) }, } - registerCommunityPackageMutationFlags(cmd, &f, true) + registerCommunityPackageMutationFlags(cmd, opts, &f, true) return cmd } @@ -156,7 +158,7 @@ func runCommunityPackageInstall(ctx context.Context, opts Options, name string, if err := validateOutput(f.output); err != nil { return err } - request := n8n.InstallCommunityPackageRequest{Name: name, Version: f.version, Verify: n8n.Bool(f.verify)} + request := n8n.InstallCommunityPackageRequest{Name: name, Version: f.version} if err := request.Validate(); err != nil { return err } @@ -191,10 +193,11 @@ func newCommunityPackageUpdateCommand(opts Options) *cobra.Command { Use: "update ", Short: "Update an installed community package", Long: "Update one installed community node package on the selected n8n instance.\n\n" + - "Omit --version to update to the version selected by n8n. Verification against\n" + - "n8n's vetted package list is enabled by default; --verify=false explicitly\n" + - "permits unverified code when the instance allows it. Updating code can change\n" + - "node behavior in existing workflows, though it does not delete those workflows.\n\n" + + "--version takes a semver version or an npm dist-tag such as latest or beta.\n" + + "Omit it to send no body and update to the latest version n8n allows. Whether\n" + + "unverified versions may be installed is an instance setting: when it is off,\n" + + "only versions verified by n8n install. Updating code can change node behavior\n" + + "in existing workflows, though it does not delete those workflows.\n\n" + "Interactive runs ask before updating. Non-interactive runs fail unless --yes is\n" + "passed. Requires API-key authentication and communityPackage:update.\n" + "Next step: run 'n8n community-package list' and test affected workflows.", @@ -206,7 +209,7 @@ func newCommunityPackageUpdateCommand(opts Options) *cobra.Command { return runCommunityPackageUpdate(cmd.Context(), opts, args[0], f) }, } - registerCommunityPackageMutationFlags(cmd, &f, true) + registerCommunityPackageMutationFlags(cmd, opts, &f, true) return cmd } @@ -214,7 +217,7 @@ func runCommunityPackageUpdate(ctx context.Context, opts Options, name string, f if err := validateOutput(f.output); err != nil { return err } - request := n8n.UpdateCommunityPackageRequest{Version: f.version, Verify: n8n.Bool(f.verify)} + request := n8n.UpdateCommunityPackageRequest{Version: f.version} if err := validateCommunityPackageArgument(name); err != nil { return err } @@ -228,7 +231,7 @@ func runCommunityPackageUpdate(ctx context.Context, opts Options, name string, f if err := requireAPIKey(resolution, "community-package"); err != nil { return err } - target := "the version selected by n8n" + target := "the latest version n8n allows" if f.version != "" { target = "version " + f.version } @@ -266,7 +269,7 @@ func newCommunityPackageUninstallCommand(opts Options) *cobra.Command { return runCommunityPackageUninstall(cmd.Context(), opts, args[0], f) }, } - registerCommunityPackageMutationFlags(cmd, &f, false) + registerCommunityPackageMutationFlags(cmd, opts, &f, false) return cmd } @@ -301,11 +304,17 @@ func runCommunityPackageUninstall(ctx context.Context, opts Options, name string return nil } -func registerCommunityPackageMutationFlags(cmd *cobra.Command, f *communityPackageMutationFlags, withPackageOptions bool) { +func registerCommunityPackageMutationFlags(cmd *cobra.Command, opts Options, f *communityPackageMutationFlags, withPackageOptions bool) { f.instance.register(cmd) if withPackageOptions { - cmd.Flags().StringVar(&f.version, "version", "", "npm package version, e.g. 1.2.3 (default: let n8n select the version)") - cmd.Flags().BoolVar(&f.verify, "verify", true, "verify against n8n's vetted package list (default true; --verify=false permits unverified code when allowed)") + // Deprecation notices go to the flag set output; cobra would otherwise + // print them on stdout, which carries the result or JSON document. + cmd.Flags().SetOutput(opts.Streams.Err) + cmd.Flags().StringVar(&f.version, "version", "", "npm semver version or dist-tag, e.g. 1.2.3 or beta (default: let n8n select the version)") + // The API dropped the verify field; the flag still parses so existing + // scripts keep working, but its value is never sent. + cmd.Flags().BoolVar(&f.verify, "verify", true, "ignored; the instance setting for unverified packages now controls verification (default true)") + _ = cmd.Flags().MarkDeprecated("verify", "it is ignored: the instance setting for unverified community packages now controls verification") } cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm the instance-changing action without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (default text; json is stable for scripting)") diff --git a/internal/cli/community_package_test.go b/internal/cli/community_package_test.go index e984d16..48b5f46 100644 --- a/internal/cli/community_package_test.go +++ b/internal/cli/community_package_test.go @@ -82,7 +82,7 @@ func TestCommunityPackageListEmpty(t *testing.T) { func TestCommunityPackageInstall(t *testing.T) { f := communityPackageFixture(t, cliCommunityPackage) f.stdin = "yes\n" - got := f.run("community-package", "install", "n8n-nodes-example", "--version", "1.2.3", "--verify=false") + got := f.run("community-package", "install", "n8n-nodes-example", "--version", "1.2.3") if got.code != ExitSuccess { t.Fatalf("exit code = %d, want %d (stderr: %s)", got.code, ExitSuccess, got.stderr) } @@ -98,7 +98,7 @@ func TestCommunityPackageInstall(t *testing.T) { if req.Method != http.MethodPost || req.URL.Path != n8n.BasePath+n8n.CommunityPackagesPath { t.Errorf("request = %s %s, want POST collection", req.Method, req.URL.Path) } - assertCLIJSON(t, `{"name":"n8n-nodes-example","version":"1.2.3","verify":false}`, f.lastBody()) + assertCLIJSON(t, `{"name":"n8n-nodes-example","version":"1.2.3"}`, f.lastBody()) } func TestCommunityPackageInstallJSONNonInteractive(t *testing.T) { @@ -115,7 +115,67 @@ func TestCommunityPackageInstallJSONNonInteractive(t *testing.T) { if err := json.Unmarshal([]byte(got.stdout), &pkg); err != nil || pkg.PackageName != "n8n-nodes-example" { t.Errorf("stdout = %q, want package JSON (error: %v)", got.stdout, err) } - assertCLIJSON(t, `{"name":"n8n-nodes-example","verify":true}`, f.lastBody()) + assertCLIJSON(t, `{"name":"n8n-nodes-example"}`, f.lastBody()) +} + +func TestCommunityPackageInstallScopedName(t *testing.T) { + f := communityPackageFixture(t, cliCommunityPackage) + got := f.run("community-package", "install", "@acme/n8n-nodes-example", "--version", "beta", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit code = %d, want %d (stderr: %s)", got.code, ExitSuccess, got.stderr) + } + if req := f.lastRequest(); req.URL.EscapedPath() != n8n.BasePath+n8n.CommunityPackagesPath { + t.Errorf("escaped path = %q, want the collection", req.URL.EscapedPath()) + } + assertCLIJSON(t, `{"name":"@acme/n8n-nodes-example","version":"beta"}`, f.lastBody()) +} + +func TestCommunityPackageDeprecatedVerifyFlag(t *testing.T) { + tests := []struct { + name string + args []string + want string + }{ + {name: "install", args: []string{"community-package", "install", "n8n-nodes-example", "--verify=false", "--yes", "--output", "json"}, want: `{"name":"n8n-nodes-example"}`}, + {name: "update", args: []string{"community-package", "update", "n8n-nodes-example", "--version", "2.0.0", "--verify=false", "--yes", "--output", "json"}, want: `{"version":"2.0.0"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := communityPackageFixture(t, cliCommunityPackage) + got := f.run(tt.args...) + if got.code != ExitSuccess { + t.Fatalf("exit code = %d, want %d (stderr: %s)", got.code, ExitSuccess, got.stderr) + } + if !strings.Contains(got.stderr, "Flag --verify has been deprecated") || !strings.Contains(got.stderr, "instance setting") { + t.Errorf("stderr = %q, want deprecation naming the instance setting", got.stderr) + } + assertCLIJSON(t, tt.want, f.lastBody()) + var pkg n8n.CommunityPackage + if err := json.Unmarshal([]byte(got.stdout), &pkg); err != nil { + t.Errorf("stdout = %q, want only package JSON (error: %v)", got.stdout, err) + } + + help := run(t, "community-package", tt.name, "--help") + if strings.Contains(help.stdout, "--verify") { + t.Errorf("help lists deprecated --verify:\n%s", help.stdout) + } + }) + } +} + +func TestCommunityPackageUpdateWithoutVersionSendsNoBody(t *testing.T) { + f := communityPackageFixture(t, cliCommunityPackage) + f.stdin = "yes\n" + got := f.run("community-package", "update", "n8n-nodes-example") + if got.code != ExitSuccess { + t.Fatalf("exit code = %d, want %d (stderr: %s)", got.code, ExitSuccess, got.stderr) + } + if !strings.Contains(got.stderr, "latest version") { + t.Errorf("stderr = %q, want confirmation naming the latest version", got.stderr) + } + if body := f.lastBody(); body != "" { + t.Errorf("body = %q, want none so n8n selects the latest version", body) + } } func TestCommunityPackageUpdateEscapesName(t *testing.T) { @@ -136,7 +196,7 @@ func TestCommunityPackageUpdateEscapesName(t *testing.T) { if req.URL.RawQuery != "" { t.Errorf("query = %q, want empty", req.URL.RawQuery) } - assertCLIJSON(t, `{"version":"1.3.0","verify":true}`, f.lastBody()) + assertCLIJSON(t, `{"version":"1.3.0"}`, f.lastBody()) } func TestCommunityPackageUninstall(t *testing.T) { diff --git a/internal/cli/user.go b/internal/cli/user.go index b732f42..de5273b 100644 --- a/internal/cli/user.go +++ b/internal/cli/user.go @@ -31,12 +31,13 @@ func newUserCommand(opts Options) *cobra.Command { "access.\n\n" + "Create accepts a strict JSON array and preserves every per-user success or\n" + "error. Role changes and deletion accept the exact user ID or email allowed by\n" + - "the API. Deletion always requires confirmation.", + "the API. Deletion always requires confirmation and deletes the user's workflows\n" + + "and credentials unless --transfer-to-project moves them to a project.", Example: " n8n user list --include-role\n" + " n8n user get person@example.com --include-role\n" + " n8n user create --input users.json\n" + " n8n user role set USER_ID global:member\n" + - " n8n user delete USER_ID --yes", + " n8n user delete USER_ID --transfer-to-project PROJECT_ID --yes", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } @@ -53,7 +54,7 @@ func newUserCommand(opts Options) *cobra.Command { type userListFlags struct { instance instanceFlags limit int - offset int + offset int // deprecated and ignored: GET /users has no offset cursor string all bool includeRole bool @@ -68,23 +69,28 @@ func newUserListCommand(opts Options) *cobra.Command { Short: "List instance or project users", Long: "List users visible to the selected credential. Use --project-id to filter to\n" + "one project's members and --include-role to request global roles. The API is\n" + - "cursor-paginated; --offset selects a starting position, while --cursor resumes\n" + - "a previous response. They cannot be combined.\n\n" + + "cursor-paginated: --cursor resumes from the nextCursor of a previous response.\n\n" + "--all follows cursors and collects at most 10,000 users. Instance-wide listing\n" + "may require the instance owner. Requires user:list.\n\n" + cursorCollectionHelp, Example: " n8n user list --include-role\n" + " n8n user list --project-id PROJECT_ID --limit 50\n" + - " n8n user list --offset 100 --output json\n" + + " n8n user list --cursor NEXT_CURSOR --output json\n" + " n8n user list --all --include-role --output json", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return runUserList(cmd.Context(), opts, f) }, } + // Deprecation notices go to the flag set output; cobra would otherwise + // print them on stdout, which carries the user list or JSON page. + cmd.Flags().SetOutput(opts.Streams.Err) f.instance.register(cmd) cmd.Flags().IntVar(&f.limit, "limit", 0, "users per API page, 1 to 250 (default: server default of 100)") - cmd.Flags().IntVar(&f.offset, "offset", 0, "users to skip before first page, zero or greater (default: 0; cannot combine with --cursor)") - cmd.Flags().StringVar(&f.cursor, "cursor", "", "pagination cursor returned by a previous list (default: first page; cannot combine with --offset)") + // The API declares no offset and live servers ignore it; the flag still + // parses so existing scripts keep working, but it is never sent. + cmd.Flags().IntVar(&f.offset, "offset", 0, "ignored; the API has no offset, use --cursor (default: 0)") + _ = cmd.Flags().MarkDeprecated("offset", "it is ignored: the users API has no offset and always starts at the first page; use --cursor") + cmd.Flags().StringVar(&f.cursor, "cursor", "", "pagination cursor returned by a previous list (default: first page)") cmd.Flags().BoolVar(&f.all, "all", false, "follow every page instead of one (maximum 10,000 users; hitting it warns and sets JSON collection.truncated)") cmd.Flags().BoolVar(&f.includeRole, "include-role", false, "include each user's global role (default: role is omitted by API)") cmd.Flags().StringVar(&f.projectID, "project-id", "", "return members of this project ID (default: all visible instance users)") @@ -98,7 +104,6 @@ func runUserList(ctx context.Context, opts Options, f userListFlags) error { } listOpts := n8n.ListUsersOptions{ ListOptions: n8n.ListOptions{Limit: f.limit, Cursor: f.cursor}, - Offset: f.offset, IncludeRole: f.includeRole, ProjectID: f.projectID, } @@ -115,9 +120,6 @@ func runUserList(ctx context.Context, opts Options, f userListFlags) error { fetch := func(ctx context.Context, pagination n8n.ListOptions) (n8n.Page[n8n.User], error) { pageOpts := listOpts pageOpts.ListOptions = pagination - if pagination.Cursor != "" { - pageOpts.Offset = 0 - } return client.ListUsers(ctx, pageOpts) } page, collection, err = collectPage(ctx, fetch, listOpts.ListOptions) @@ -217,7 +219,8 @@ func newUserCreateCommand(opts Options) *cobra.Command { Use: "create", Short: "Invite one or more users", Long: "Create or invite users from a strict JSON array supplied by --input. Each item\n" + - "requires email and may set a global role slug. Unknown fields, an empty array,\n" + + "requires email and may set role: global:admin, global:member (the default),\n" + + "global:chatUser, or a custom global role slug. Unknown fields, an empty array,\n" + "invalid emails, and trailing JSON documents are refused before transport.\n\n" + "n8n returns one result per invitation. Output preserves successful users, invite\n" + "URLs, email-delivery state, and individual errors even when a bulk request is\n" + @@ -262,10 +265,11 @@ func newUserRoleCommand(opts Options) *cobra.Command { Use: "role", Short: "Manage users' global roles", Long: "Manage global role assignments for instance users. Use 'set' with a user ID\n" + - "or email and a role slug discovered through 'n8n role list'. Role changes can\n" + - "alter instance-wide permissions and may require owner access or licensing.", + "or email and a role slug: global:admin, global:member, global:chatUser, or a\n" + + "custom global role discovered through 'n8n role list'. Role changes can alter\n" + + "instance-wide permissions and may require owner access or licensing.", Example: " n8n user role set USER_ID global:member\n" + - " n8n user role set person@example.com global:admin --output json", + " n8n user role set person@example.com global:chatUser --output json", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } @@ -284,11 +288,13 @@ func newUserRoleSetCommand(opts Options) *cobra.Command { Use: "set ", Short: "Set a user's global role", Long: "Change one user's global role using the exact user ID or email accepted by the\n" + - "API. The role slug must identify an assignable global role; run 'n8n role list'\n" + - "to inspect licensing and available slugs. This can immediately change the user's\n" + - "instance permissions. Requires user:changeRole.", + "API. The role slug must identify an assignable global role: global:admin,\n" + + "global:member, global:chatUser, or a custom global role slug. Run 'n8n role\n" + + "list' to inspect licensing and available slugs. This can immediately change the\n" + + "user's instance permissions. Requires user:changeRole.", Example: " n8n user role set USER_ID global:member\n" + - " n8n user role set person@example.com global:admin --output json", + " n8n user role set person@example.com global:chatUser\n" + + " n8n user role set USER_ID CUSTOM_ROLE_SLUG --output json", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { return runUserRoleSet(cmd.Context(), opts, args[0], args[1], f) @@ -320,9 +326,10 @@ func runUserRoleSet(ctx context.Context, opts Options, identifier, role string, } type userDeleteFlags struct { - instance instanceFlags - yes bool - output string + instance instanceFlags + transferProjectID string + yes bool + output string } func newUserDeleteCommand(opts Options) *cobra.Command { @@ -331,21 +338,28 @@ func newUserDeleteCommand(opts Options) *cobra.Command { Use: "delete ", Short: "Permanently delete a user", Long: "Permanently delete one user using the exact ID or email accepted by the API.\n" + - "This removes the account and can delete resources owned by its personal project;\n" + - "the documented endpoint provides no ownership-transfer option. It cannot be\n" + - "undone and the instance owner cannot be deleted.\n\n" + - "Interactive runs ask for confirmation. Non-interactive runs require --yes.\n" + + "By default n8n also deletes the user's workflows and credentials. Pass\n" + + "--transfer-to-project with a project ID (sent as the API's transferId) to move\n" + + "those workflows and credentials to that project instead; find IDs with\n" + + "'n8n project list'. Deletion cannot be undone and the instance owner cannot be\n" + + "deleted.\n\n" + + "Interactive runs ask for confirmation naming what happens to the user's\n" + + "workflows and credentials. Non-interactive runs require --yes.\n" + "Requires user:delete.", - Example: " n8n user delete USER_ID\n" + + Example: " n8n user delete USER_ID --transfer-to-project PROJECT_ID\n" + " n8n user delete person@example.com --yes --output json", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + if cmd.Flags().Changed("transfer-to-project") && f.transferProjectID == "" { + return fmt.Errorf("--transfer-to-project needs a project ID: omit the flag to delete the user's workflows and credentials instead") + } return runUserDelete(cmd.Context(), opts, args[0], f) }, } f.instance.register(cmd) - cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm permanent user and owned-resource deletion without prompting (required when stdin is not interactive)") - cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (acknowledgement contains only deleted user identifier)") + cmd.Flags().StringVar(&f.transferProjectID, "transfer-to-project", "", "project ID that receives the user's workflows and credentials (default: none, they are deleted with the user)") + cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm permanent user deletion, and deletion of their workflows and credentials unless transferred, without prompting (required when stdin is not interactive)") + cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (acknowledgement contains deleted user identifier and any transfer project ID)") return cmd } @@ -356,18 +370,25 @@ func runUserDelete(ctx context.Context, opts Options, identifier string, f userD if err := validateUserIdentifier(identifier); err != nil { return err } + if strings.TrimSpace(f.transferProjectID) != f.transferProjectID { + return fmt.Errorf("--transfer-to-project project ID must not start or end with whitespace") + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err } - question := fmt.Sprintf("Permanently delete user %q from %s? Their account and owned personal-project resources may be deleted.", identifier, resolution.URL) + fate := "Their workflows and credentials will be permanently deleted too; pass --transfer-to-project to keep them." + if f.transferProjectID != "" { + fate = fmt.Sprintf("Their workflows and credentials will move to project %q.", f.transferProjectID) + } + question := fmt.Sprintf("Permanently delete user %q from %s? %s", identifier, resolution.URL, fate) if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } - if err := client.DeleteUser(ctx, identifier); err != nil { + if err := client.DeleteUser(ctx, identifier, n8n.DeleteUserOptions{TransferProjectID: f.transferProjectID}); err != nil { return userAPIError(err, resolution, "delete") } - return writeUserMutation(opts, resolution, userMutation{Action: "deleted", Identifier: identifier}, f.output) + return writeUserMutation(opts, resolution, userMutation{Action: "deleted", Identifier: identifier, TransferProjectID: f.transferProjectID}, f.output) } func readUserDocument(opts Options, path string, dst any) error { @@ -453,9 +474,10 @@ func writeCreateUserResults(opts Options, resolution config.Resolution, results } type userMutation struct { - Action string `json:"action"` - Identifier string `json:"identifier"` - Role string `json:"role,omitempty"` + Action string `json:"action"` + Identifier string `json:"identifier"` + Role string `json:"role,omitempty"` + TransferProjectID string `json:"transferProjectId,omitempty"` } func writeUserMutation(opts Options, resolution config.Resolution, result userMutation, output string) error { @@ -468,6 +490,9 @@ func writeUserMutation(opts Options, resolution config.Resolution, result userMu if result.Role != "" { fmt.Fprintf(tw, "Role:\t%s\n", result.Role) } + if result.TransferProjectID != "" { + fmt.Fprintf(tw, "Transferred to project:\t%s\n", result.TransferProjectID) + } fmt.Fprintf(tw, "Instance:\t%s\n", resolution.URL) return tw.Flush() } diff --git a/internal/cli/user_test.go b/internal/cli/user_test.go index 740a005..9e1c8ba 100644 --- a/internal/cli/user_test.go +++ b/internal/cli/user_test.go @@ -31,7 +31,7 @@ func userFixture(t *testing.T, body string) *fixture { func TestUserListTextJSONAndPagination(t *testing.T) { f := userFixture(t, `{"data":[`+cliUser+`],"nextCursor":"next/one?x=1"}`) - got := f.run("user", "list", "--limit", "50", "--offset", "25", "--include-role", "--project-id", "project/one?x=1") + got := f.run("user", "list", "--limit", "50", "--include-role", "--project-id", "project/one?x=1") if got.code != ExitSuccess { t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) } @@ -42,7 +42,7 @@ func TestUserListTextJSONAndPagination(t *testing.T) { } req := f.lastRequest() query := req.URL.Query() - if req.Method != http.MethodGet || req.URL.Path != n8n.BasePath+n8n.UsersPath || query.Get("limit") != "50" || query.Get("offset") != "25" || query.Get("includeRole") != "true" || query.Get("projectId") != "project/one?x=1" { + if req.Method != http.MethodGet || req.URL.Path != n8n.BasePath+n8n.UsersPath || query.Get("limit") != "50" || query.Get("includeRole") != "true" || query.Get("projectId") != "project/one?x=1" { t.Errorf("request = %s %s?%s", req.Method, req.URL.Path, req.URL.RawQuery) } @@ -66,7 +66,7 @@ func TestUserListAllKeepsFiltersAndFollowsCursor(t *testing.T) { pending = strings.Replace(pending, `"email":"person@example.com"`, `"email":"two@example.com"`, 1) return `{"data":[` + pending + `],"nextCursor":null}` } - got := f.run("user", "list", "--all", "--offset", "5", "--limit", "1", "--include-role", "--project-id", "project-1", "--output", "json") + got := f.run("user", "list", "--all", "--limit", "1", "--include-role", "--project-id", "project-1", "--output", "json") if got.code != ExitSuccess { t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) } @@ -81,10 +81,10 @@ func TestUserListAllKeepsFiltersAndFollowsCursor(t *testing.T) { t.Fatalf("requests = %d, want login plus two user pages", len(requests)) } first, second := requests[len(requests)-2], requests[len(requests)-1] - if first.URL.Query().Get("offset") != "5" || first.URL.Query().Get("cursor") != "" { + if first.URL.Query().Get("cursor") != "" { t.Errorf("first query = %q", first.URL.RawQuery) } - if second.URL.Query().Get("offset") != "" || second.URL.Query().Get("cursor") != "next/one?x=1" { + if second.URL.Query().Get("cursor") != "next/one?x=1" { t.Errorf("second query = %q", second.URL.RawQuery) } for _, req := range []*http.Request{first, second} { @@ -94,6 +94,30 @@ func TestUserListAllKeepsFiltersAndFollowsCursor(t *testing.T) { } } +func TestUserListDeprecatedOffsetIsIgnored(t *testing.T) { + f := userFixture(t, `{"data":[`+cliUser+`],"nextCursor":null}`) + got := f.run("user", "list", "--offset", "25", "--cursor", "next", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if !strings.Contains(got.stderr, "Flag --offset has been deprecated") || !strings.Contains(got.stderr, "use --cursor") { + t.Errorf("stderr = %q, want deprecation pointing at --cursor", got.stderr) + } + var page n8n.Page[n8n.User] + if err := json.Unmarshal([]byte(got.stdout), &page); err != nil { + t.Errorf("stdout = %q, want only the JSON page (error: %v)", got.stdout, err) + } + query := f.lastRequest().URL.Query() + if query.Has("offset") || query.Get("cursor") != "next" { + t.Errorf("query = %q, want cursor and no offset", f.lastRequest().URL.RawQuery) + } + + help := run(t, "user", "list", "--help") + if strings.Contains(help.stdout, "--offset") { + t.Errorf("help lists deprecated --offset:\n%s", help.stdout) + } +} + func TestUserGetByEmailEscapesPath(t *testing.T) { f := userFixture(t, cliUser) got := f.run("user", "get", "person+ops@example.com/one?x=1", "--include-role") @@ -163,7 +187,7 @@ func TestUserRoleSetAndDelete(t *testing.T) { before := f.requestCount() f.stdin = "no\n" got := f.run("user", "delete", "person@example.com") - if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || !strings.Contains(got.stderr, "owned personal-project resources") || f.requestCount() != before { + if got.code != ExitError || !strings.Contains(got.stderr, "aborted") || !strings.Contains(got.stderr, "workflows and credentials will be permanently deleted") || f.requestCount() != before { t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) } f.interactive = false @@ -176,8 +200,43 @@ func TestUserRoleSetAndDelete(t *testing.T) { t.Fatalf("confirmed exit = %d, stderr: %s", got.code, got.stderr) } req := f.lastRequest() - if req.Method != http.MethodDelete || req.URL.EscapedPath() != n8n.BasePath+"/users/person+ops@example.com%2Fone%3Fx=1" { - t.Errorf("request = %s %s", req.Method, req.URL.EscapedPath()) + if req.Method != http.MethodDelete || req.URL.EscapedPath() != n8n.BasePath+"/users/person+ops@example.com%2Fone%3Fx=1" || req.URL.RawQuery != "" { + t.Errorf("request = %s %s?%s, want no transferId", req.Method, req.URL.EscapedPath(), req.URL.RawQuery) + } + var result userMutation + if err := json.Unmarshal([]byte(got.stdout), &result); err != nil || result.TransferProjectID != "" { + t.Errorf("stdout = %q, want acknowledgement without transfer (error: %v)", got.stdout, err) + } + }) + + t.Run("delete with transfer", func(t *testing.T) { + f := userFixture(t, "") + before := f.requestCount() + f.stdin = "no\n" + got := f.run("user", "delete", "person@example.com", "--transfer-to-project", "project/one") + if got.code != ExitError || !strings.Contains(got.stderr, `will move to project "project/one"`) || strings.Contains(got.stderr, "permanently deleted too") || f.requestCount() != before { + t.Errorf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + f.interactive = false + got = f.run("user", "delete", "person@example.com", "--transfer-to-project", "project/one") + if got.code != ExitError || !strings.Contains(got.stderr, "pass --yes") || f.requestCount() != before { + t.Errorf("non-interactive result = %+v", got) + } + got = f.run("user", "delete", "person@example.com", "--transfer-to-project", "project/one", "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("confirmed exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodDelete || req.URL.Query().Get("transferId") != "project/one" { + t.Errorf("request = %s %s?%s, want transferId", req.Method, req.URL.EscapedPath(), req.URL.RawQuery) + } + var result userMutation + if err := json.Unmarshal([]byte(got.stdout), &result); err != nil || result.TransferProjectID != "project/one" { + t.Errorf("stdout = %q, want transfer project in acknowledgement (error: %v)", got.stdout, err) + } + got = f.run("user", "delete", "person@example.com", "--transfer-to-project", "project/one", "--yes") + if got.code != ExitSuccess || !strings.Contains(got.stdout, "Transferred to project:") { + t.Errorf("text result = %+v, want transfer line", got) } }) } @@ -189,7 +248,6 @@ func TestUserValidationBeforeRequest(t *testing.T) { args []string want string }{ - {name: "offset with cursor", args: []string{"user", "list", "--offset", "1", "--cursor", "next"}, want: "cannot be used together"}, {name: "large limit", args: []string{"user", "list", "--limit", "251"}, want: "must not exceed 250"}, {name: "missing input", args: []string{"user", "create"}, want: "--input is required"}, {name: "unknown input field", stdin: `[{"email":"one@example.com","name":"One"}]`, args: []string{"user", "create", "--input", "-"}, want: "unknown field"}, @@ -199,6 +257,8 @@ func TestUserValidationBeforeRequest(t *testing.T) { {name: "blank get identifier", args: []string{"user", "get", " "}, want: "ID or email is required"}, {name: "blank role", args: []string{"user", "role", "set", "person@example.com", " "}, want: "role slug is required"}, {name: "padded delete identifier", args: []string{"user", "delete", " person@example.com", "--yes"}, want: "whitespace"}, + {name: "empty transfer project", args: []string{"user", "delete", "person@example.com", "--transfer-to-project", "", "--yes"}, want: "needs a project ID"}, + {name: "padded transfer project", args: []string{"user", "delete", "person@example.com", "--transfer-to-project", " p1", "--yes"}, want: "whitespace"}, {name: "unknown output", args: []string{"user", "list", "--output", "yaml"}, want: "unknown output format"}, } for _, tt := range tests { diff --git a/internal/n8n/community_package.go b/internal/n8n/community_package.go index 39223ad..fca7015 100644 --- a/internal/n8n/community_package.go +++ b/internal/n8n/community_package.go @@ -32,12 +32,11 @@ type CommunityPackageNode struct { } // InstallCommunityPackageRequest selects the npm package and version to -// install. Verify is a pointer because the API distinguishes an omitted value -// from false; use [Bool] when setting it directly. +// install. The API no longer accepts a verify field: the instance setting for +// unverified packages decides which versions may be installed. type InstallCommunityPackageRequest struct { Name string `json:"name"` Version string `json:"version,omitempty"` - Verify *bool `json:"verify,omitempty"` } // Validate checks the required package name before a request is sent. @@ -49,8 +48,8 @@ func (r InstallCommunityPackageRequest) Validate() error { if name != r.Name { return fmt.Errorf("community package name must not start or end with whitespace") } - if !strings.HasPrefix(name, "n8n-nodes-") { - return fmt.Errorf("community package name %q must start with %q", name, "n8n-nodes-") + if !validCommunityPackageName(name) { + return fmt.Errorf("community package name %q must have the form n8n-nodes- or @/n8n-nodes-", name) } if strings.TrimSpace(r.Version) != r.Version { return fmt.Errorf("community package version must not start or end with whitespace") @@ -58,12 +57,11 @@ func (r InstallCommunityPackageRequest) Validate() error { return nil } -// UpdateCommunityPackageRequest selects an optional target version and package -// verification policy. Its zero value sends no body, asking n8n to use its -// defaults (latest version and verification enabled). +// UpdateCommunityPackageRequest selects an optional target version. The API +// declares the body optional, so its zero value sends no body and n8n updates +// to the latest version the instance setting for unverified packages allows. type UpdateCommunityPackageRequest struct { Version string `json:"version,omitempty"` - Verify *bool `json:"verify,omitempty"` } // Validate checks update options before a request is sent. @@ -75,7 +73,20 @@ func (r UpdateCommunityPackageRequest) Validate() error { } func (r UpdateCommunityPackageRequest) empty() bool { - return r.Version == "" && r.Verify == nil + return r.Version == "" +} + +// validCommunityPackageName accepts the two npm name forms n8n installs: +// unscoped n8n-nodes- and scoped @/n8n-nodes-. +func validCommunityPackageName(name string) bool { + if scoped, ok := strings.CutPrefix(name, "@"); ok { + scope, rest, found := strings.Cut(scoped, "/") + if !found || scope == "" || strings.Contains(rest, "/") { + return false + } + name = rest + } + return strings.HasPrefix(name, "n8n-nodes-") && len(name) > len("n8n-nodes-") } // Bool returns a pointer to value for optional boolean request fields. diff --git a/internal/n8n/community_package_test.go b/internal/n8n/community_package_test.go index b9cba49..b7264f5 100644 --- a/internal/n8n/community_package_test.go +++ b/internal/n8n/community_package_test.go @@ -127,7 +127,7 @@ func TestListCommunityPackagesEmpty(t *testing.T) { func TestInstallCommunityPackage(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, communityPackageBody)) - request := InstallCommunityPackageRequest{Name: "n8n-nodes-example", Version: "1.2.3", Verify: Bool(false)} + request := InstallCommunityPackageRequest{Name: "n8n-nodes-example", Version: "1.2.3"} installed, err := server.client(t).InstallCommunityPackage(context.Background(), request) if err != nil { @@ -140,7 +140,7 @@ func TestInstallCommunityPackage(t *testing.T) { if req.Header.Get("Content-Type") != contentTypeJSON { t.Errorf("Content-Type = %q, want %q", req.Header.Get("Content-Type"), contentTypeJSON) } - assertJSONEqual(t, `{"name":"n8n-nodes-example","version":"1.2.3","verify":false}`, body) + assertJSONEqual(t, `{"name":"n8n-nodes-example","version":"1.2.3"}`, body) if installed.PackageName != request.Name || installed.InstalledVersion != request.Version { t.Errorf("installed = %+v, want requested package and version", installed) } @@ -156,10 +156,23 @@ func TestInstallCommunityPackageOptionalFields(t *testing.T) { assertJSONEqual(t, `{"name":"n8n-nodes-example"}`, body) } +func TestInstallCommunityPackageScopedName(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, communityPackageBody)) + request := InstallCommunityPackageRequest{Name: "@acme/n8n-nodes-example", Version: "beta"} + if _, err := server.client(t).InstallCommunityPackage(context.Background(), request); err != nil { + t.Fatalf("InstallCommunityPackage: %v", err) + } + req, body := server.last(t) + if req.URL.EscapedPath() != BasePath+CommunityPackagesPath { + t.Errorf("escaped path = %q, want the collection; the scoped name belongs in the body", req.URL.EscapedPath()) + } + assertJSONEqual(t, `{"name":"@acme/n8n-nodes-example","version":"beta"}`, body) +} + func TestUpdateCommunityPackage(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, communityPackageBody)) name := "@scope/n8n-nodes-example?channel=next#node" - request := UpdateCommunityPackageRequest{Version: "1.3.0", Verify: Bool(false)} + request := UpdateCommunityPackageRequest{Version: "1.3.0"} updated, err := server.client(t).UpdateCommunityPackage(context.Background(), name, request) if err != nil { @@ -176,7 +189,7 @@ func TestUpdateCommunityPackage(t *testing.T) { if req.URL.RawQuery != "" { t.Errorf("query = %q, want empty; package punctuation belongs in the path", req.URL.RawQuery) } - assertJSONEqual(t, `{"version":"1.3.0","verify":false}`, body) + assertJSONEqual(t, `{"version":"1.3.0"}`, body) if updated.PackageName != "n8n-nodes-example" { t.Errorf("updated package = %+v", updated) } @@ -267,7 +280,27 @@ func TestCommunityPackageValidationBeforeRequest(t *testing.T) { {name: "install wrong prefix", call: func(c *Client) error { _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "example"}) return err - }, want: "must start"}, + }, want: "must have the form"}, + {name: "install bare prefix", call: func(c *Client) error { + _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "n8n-nodes-"}) + return err + }, want: "must have the form"}, + {name: "install scoped wrong prefix", call: func(c *Client) error { + _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "@acme/example"}) + return err + }, want: "must have the form"}, + {name: "install empty scope", call: func(c *Client) error { + _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "@/n8n-nodes-example"}) + return err + }, want: "must have the form"}, + {name: "install scope without slash", call: func(c *Client) error { + _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "@n8n-nodes-example"}) + return err + }, want: "must have the form"}, + {name: "install nested path", call: func(c *Client) error { + _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: "@acme/n8n-nodes-example/extra"}) + return err + }, want: "must have the form"}, {name: "install padded name", call: func(c *Client) error { _, err := c.InstallCommunityPackage(context.Background(), InstallCommunityPackageRequest{Name: " n8n-nodes-example"}) return err diff --git a/internal/n8n/user.go b/internal/n8n/user.go index 125ceca..b3a520e 100644 --- a/internal/n8n/user.go +++ b/internal/n8n/user.go @@ -6,7 +6,6 @@ import ( "net/http" "net/mail" "net/url" - "strconv" "strings" ) @@ -26,11 +25,11 @@ type User struct { MFAEnabled bool `json:"mfaEnabled"` } -// ListUsersOptions contains pagination and user-specific filters. +// ListUsersOptions contains pagination and user-specific filters. GET /users +// declares no offset parameter and servers ignore one, so paging is +// cursor-only. type ListUsersOptions struct { ListOptions - // Offset skips this many users. It cannot be combined with Cursor. - Offset int // IncludeRole asks n8n to include each user's global role. IncludeRole bool // ProjectID limits results to members of one project. @@ -45,20 +44,11 @@ func (o ListUsersOptions) Validate() error { if o.Limit > 250 { return fmt.Errorf("limit must not exceed 250, got %d", o.Limit) } - if o.Offset < 0 { - return fmt.Errorf("offset must not be negative, got %d", o.Offset) - } - if o.Offset > 0 && o.Cursor != "" { - return fmt.Errorf("offset and cursor cannot be used together") - } return validateUserText("project ID", o.ProjectID, false) } func (o ListUsersOptions) apply() url.Values { query := o.ListOptions.Apply(nil) - if o.Offset > 0 { - query.Set("offset", strconv.Itoa(o.Offset)) - } if o.IncludeRole { query.Set("includeRole", "true") } @@ -151,12 +141,27 @@ func (c *Client) ChangeUserRole(ctx context.Context, identifier, role string) er return err } -// DeleteUser permanently removes one user by ID or email. -func (c *Client) DeleteUser(ctx context.Context, identifier string) error { +// DeleteUserOptions controls what happens to resources the deleted user owns. +type DeleteUserOptions struct { + // TransferProjectID moves the user's workflows and credentials to this + // project (query parameter transferId). Empty deletes them with the user. + TransferProjectID string +} + +// DeleteUser permanently removes one user by ID or email. Without a transfer +// project, n8n deletes the user's workflows and credentials too. +func (c *Client) DeleteUser(ctx context.Context, identifier string, opts DeleteUserOptions) error { if err := validateUserIdentifier(identifier); err != nil { return err } - _, err := c.Do(ctx, Request{Method: http.MethodDelete, Path: PathJoin("users", identifier)}, nil) + if err := validateUserText("transfer project ID", opts.TransferProjectID, false); err != nil { + return err + } + query := make(url.Values) + if opts.TransferProjectID != "" { + query.Set("transferId", opts.TransferProjectID) + } + _, err := c.Do(ctx, Request{Method: http.MethodDelete, Path: PathJoin("users", identifier), Query: query}, nil) return err } diff --git a/internal/n8n/user_test.go b/internal/n8n/user_test.go index ddd6516..a3e1aff 100644 --- a/internal/n8n/user_test.go +++ b/internal/n8n/user_test.go @@ -23,7 +23,7 @@ const userResponse = `{ func TestListUsersQueryAuthAndDecoding(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{"data":[`+userResponse+`],"nextCursor":"next/one?x=1"}`)) page, err := server.client(t).ListUsers(context.Background(), ListUsersOptions{ - ListOptions: ListOptions{Limit: 50}, Offset: 25, IncludeRole: true, ProjectID: "project/one?x=1", + ListOptions: ListOptions{Limit: 50}, IncludeRole: true, ProjectID: "project/one?x=1", }) if err != nil { t.Fatalf("ListUsers: %v", err) @@ -33,9 +33,12 @@ func TestListUsersQueryAuthAndDecoding(t *testing.T) { t.Errorf("request = %s %s, want GET %s", req.Method, req.URL.Path, BasePath+UsersPath) } query := req.URL.Query() - if query.Get("limit") != "50" || query.Get("offset") != "25" || query.Get("includeRole") != "true" || query.Get("projectId") != "project/one?x=1" { + if query.Get("limit") != "50" || query.Get("includeRole") != "true" || query.Get("projectId") != "project/one?x=1" { t.Errorf("query = %q", req.URL.RawQuery) } + if query.Has("offset") { + t.Errorf("query = %q, want no offset; GET /users declares none", req.URL.RawQuery) + } if body != "" { t.Errorf("body = %q, want empty", body) } @@ -112,8 +115,11 @@ func TestGetChangeRoleAndDeleteUser(t *testing.T) { return c.ChangeUserRole(context.Background(), identifier, "global:custom/role") }, method: http.MethodPatch, path: "/users/person+ops@example.com%2Fone%3Fx=1/role", body: `{"newRoleName":"global:custom/role"}`, status: http.StatusNoContent}, {name: "delete", call: func(c *Client) error { - return c.DeleteUser(context.Background(), identifier) + return c.DeleteUser(context.Background(), identifier, DeleteUserOptions{}) }, method: http.MethodDelete, path: "/users/person+ops@example.com%2Fone%3Fx=1", status: http.StatusNoContent}, + {name: "delete with transfer", call: func(c *Client) error { + return c.DeleteUser(context.Background(), identifier, DeleteUserOptions{TransferProjectID: "project/one?x=1"}) + }, method: http.MethodDelete, path: "/users/person+ops@example.com%2Fone%3Fx=1", query: "transferId=project%2Fone%3Fx%3D1", status: http.StatusNoContent}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -157,18 +163,10 @@ func TestUserValidationBeforeRequest(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{}`)) client := server.client(t) calls := map[string]func() error{ - "negative offset": func() error { - _, err := client.ListUsers(context.Background(), ListUsersOptions{Offset: -1}) - return err - }, "large limit": func() error { _, err := client.ListUsers(context.Background(), ListUsersOptions{ListOptions: ListOptions{Limit: 251}}) return err }, - "offset with cursor": func() error { - _, err := client.ListUsers(context.Background(), ListUsersOptions{ListOptions: ListOptions{Cursor: "next"}, Offset: 1}) - return err - }, "empty invitations": func() error { _, err := client.CreateUsers(context.Background(), nil) return err @@ -189,7 +187,10 @@ func TestUserValidationBeforeRequest(t *testing.T) { return client.ChangeUserRole(context.Background(), "one@example.com", " ") }, "padded delete identifier": func() error { - return client.DeleteUser(context.Background(), " one@example.com") + return client.DeleteUser(context.Background(), " one@example.com", DeleteUserOptions{}) + }, + "padded transfer project": func() error { + return client.DeleteUser(context.Background(), "one@example.com", DeleteUserOptions{TransferProjectID: "project "}) }, } for name, call := range calls { diff --git a/test/integration/community_package_test.go b/test/integration/community_package_test.go index dc047f7..52e748f 100644 --- a/test/integration/community_package_test.go +++ b/test/integration/community_package_test.go @@ -73,7 +73,7 @@ func TestCommunityPackageLifecycle(t *testing.T) { }) pkg, err := client.InstallCommunityPackage(context.Background(), n8n.InstallCommunityPackageRequest{ - Name: name, Version: installVersion, Verify: n8n.Bool(true), + Name: name, Version: installVersion, }) if err != nil { t.Fatalf("InstallCommunityPackage: %v", err) @@ -84,7 +84,7 @@ func TestCommunityPackageLifecycle(t *testing.T) { } pkg, err = client.UpdateCommunityPackage(context.Background(), name, n8n.UpdateCommunityPackageRequest{ - Version: updateVersion, Verify: n8n.Bool(true), + Version: updateVersion, }) if err != nil { t.Fatalf("UpdateCommunityPackage: %v", err)