Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions shortcuts/mail/mail_template_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package mail

import (
"context"
"fmt"
"io"
"strings"

"github.com/larksuite/cli/internal/output"
"github.com/larksuite/cli/shortcuts/common"
)

// MailTemplateCreate creates a new email template.
var MailTemplateCreate = common.Shortcut{
Service: "mail",
Command: "+template-create",
Description: "Create a new email template. The --body value is written to the request body as body_html (auto-detected HTML or plain text). Use --plain-text to force plain-text mode.",
Risk: "write",
Scopes: []string{"mail:user_mailbox.message:modify"},
AuthTypes: []string{"user"},
HasFormat: true,
Flags: []common.Flag{
{Name: "name", Desc: "Required. Template name (max 100 chars)", Required: true},
{Name: "subject", Desc: "Email subject for the template"},
{Name: "body", Desc: "Email body (HTML or plain text). The value is written to body_html in the request body."},
{Name: "to", Desc: "Default To recipients, comma-separated"},
{Name: "cc", Desc: "Default CC recipients, comma-separated"},
{Name: "bcc", Desc: "Default BCC recipients, comma-separated"},
{Name: "plain-text", Type: "bool", Desc: "Force plain-text mode for body"},
{Name: "mailbox", Default: "me", Desc: "Mailbox ID or email address (default: me)"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
name := strings.TrimSpace(runtime.Str("name"))
if name == "" {
return output.ErrValidation("--name is required")
}
if len([]rune(name)) > 100 {
return output.ErrValidation("--name exceeds 100 character limit")
}
return nil
Comment on lines +35 to +43
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use the validated name value in the request body.

Line 36 trims --name for validation, but Line 77 sends the raw flag value. That lets padded names through and can still exceed the backend limit after validation if the extra whitespace is preserved in the payload.

💡 Proposed fix
 func buildTemplateCreateBody(runtime *common.RuntimeContext) map[string]interface{} {
+	name := strings.TrimSpace(runtime.Str("name"))
 	body := map[string]interface{}{
-		"name": runtime.Str("name"),
+		"name": name,
 	}

Also applies to: 75-78

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/mail/mail_template_create.go` around lines 35 - 43, The validation
trims the name into the local variable name in Validate but the request body
later uses runtime.Str("name") (raw value), so whitespace can slip through;
change the code that builds the create-mail-template request to use the
already-trimmed and validated name variable (or set the trimmed value back into
the runtime before building the payload) so the payload contains the trimmed
name and the same length check applies (refer to Validate, the name variable,
and the code that constructs/sends the request body).

},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
mailboxID := resolveMailboxID(runtime)
return common.NewDryRunAPI().
Desc("Create a new email template").
POST(mailboxPath(mailboxID, "templates")).
Body(map[string]interface{}{"template": buildTemplateCreateBody(runtime)})
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
mailboxID := resolveMailboxID(runtime)
// Wrap the template object per IDL api.body="template" annotation so
// that apigw unwraps it into CreateUserMailboxTemplateRequest.Template.
body := map[string]interface{}{"template": buildTemplateCreateBody(runtime)}
data, err := runtime.CallAPI("POST", mailboxPath(mailboxID, "templates"), nil, body)
if err != nil {
return output.Errorf(output.ExitAPI, "api_error", "create template failed: %s", err)
}
tmpl := extractTemplateObject(data)
if tmpl == nil {
return output.Errorf(output.ExitAPI, "api_error", "create template: missing template in response")
}
runtime.OutFormat(tmpl, nil, func(w io.Writer) {
fmt.Fprintln(w, "Template created.")
fmt.Fprintf(w, "template_id: %s\n", strVal(tmpl["template_id"]))
fmt.Fprintf(w, "name: %s\n", strVal(tmpl["name"]))
})
return nil
},
}

// buildTemplateCreateBody assembles the JSON body for +template-create.
// The value of --body is always written to body_html so that the server
// receives the user-supplied content (see verification report TPL-CREATE-01).
func buildTemplateCreateBody(runtime *common.RuntimeContext) map[string]interface{} {
body := map[string]interface{}{
"name": runtime.Str("name"),
}
if s := runtime.Str("subject"); s != "" {
body["subject"] = s
}
// --body is the user's email body. It must be written to the
// request body's body_html field — the server uses body_html for both
// HTML and plain-text bodies, with is_plain_text_mode toggling the
// rendering mode.
if b := runtime.Str("body"); b != "" {
body["body_html"] = b
}
if runtime.Bool("plain-text") {
body["is_plain_text_mode"] = true
}
// Address list JSON keys match the IDL Template struct's api.json
// annotations (tos/ccs/bccs), while the --to/--cc/--bcc CLI flag names
// stay singular for a stable user surface.
if to := runtime.Str("to"); to != "" {
body["tos"] = parseAddressListForAPI(to)
}
if cc := runtime.Str("cc"); cc != "" {
body["ccs"] = parseAddressListForAPI(cc)
}
if bcc := runtime.Str("bcc"); bcc != "" {
body["bccs"] = parseAddressListForAPI(bcc)
}
return body
}

// parseAddressListForAPI converts a comma-separated recipient string into the
// open-api MailAddress array shape: [{"mail_address": "...", "name": "..."}].
// Entries with an empty email are dropped; empty input returns nil.
func parseAddressListForAPI(raw string) []map[string]interface{} {
boxes := ParseMailboxList(raw)
if len(boxes) == 0 {
return nil
}
out := make([]map[string]interface{}, 0, len(boxes))
for _, m := range boxes {
entry := map[string]interface{}{"mail_address": m.Email}
if m.Name != "" {
entry["name"] = m.Name
}
out = append(out, entry)
}
return out
}
51 changes: 51 additions & 0 deletions shortcuts/mail/mail_template_delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package mail

import (
"context"
"strings"

"github.com/larksuite/cli/internal/output"
"github.com/larksuite/cli/shortcuts/common"
)

// MailTemplateDelete deletes an email template.
var MailTemplateDelete = common.Shortcut{
Service: "mail",
Command: "+template-delete",
Description: "Delete an email template by ID.",
Risk: "delete",
Scopes: []string{"mail:user_mailbox.message:modify"},
AuthTypes: []string{"user"},
Flags: []common.Flag{
{Name: "template-id", Desc: "Required. Template ID to delete", Required: true},
{Name: "mailbox", Default: "me", Desc: "Mailbox ID or email address (default: me)"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if strings.TrimSpace(runtime.Str("template-id")) == "" {
return output.ErrValidation("--template-id is required")
}
return nil
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
mailboxID := resolveMailboxID(runtime)
templateID := runtime.Str("template-id")
return common.NewDryRunAPI().
Desc("Delete an email template").
DELETE(mailboxPath(mailboxID, "templates", templateID))
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
mailboxID := resolveMailboxID(runtime)
templateID := runtime.Str("template-id")
if _, err := runtime.CallAPI("DELETE", mailboxPath(mailboxID, "templates", templateID), nil, nil); err != nil {
return output.Errorf(output.ExitAPI, "api_error", "delete template failed: %s", err)
Comment on lines +26 to +43
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Trim template-id before building the DELETE path.

Line 27 validates the trimmed value, but Lines 34 and 41 use the raw flag. --template-id " tpl_123 " will pass validation and then hit /templates/%20tpl_123%20, which is the wrong resource.

💡 Proposed fix
 	DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
 		mailboxID := resolveMailboxID(runtime)
-		templateID := runtime.Str("template-id")
+		templateID := strings.TrimSpace(runtime.Str("template-id"))
 		return common.NewDryRunAPI().
 			Desc("Delete an email template").
 			DELETE(mailboxPath(mailboxID, "templates", templateID))
 	},
 	Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
 		mailboxID := resolveMailboxID(runtime)
-		templateID := runtime.Str("template-id")
+		templateID := strings.TrimSpace(runtime.Str("template-id"))
 		if _, err := runtime.CallAPI("DELETE", mailboxPath(mailboxID, "templates", templateID), nil, nil); err != nil {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/mail/mail_template_delete.go` around lines 26 - 43, The validation
trims the template-id but the DryRun and Execute handlers use the raw flag
value, causing encoded spaces in the path; update both DryRun and Execute to set
templateID := strings.TrimSpace(runtime.Str("template-id")) (instead of
runtime.Str(...)) so mailboxPath(mailboxID, "templates", templateID) and the
runtime.CallAPI DELETE call use the trimmed id; adjust imports if needed and
keep resolveMailboxID and mailboxPath usage unchanged.

}
runtime.Out(map[string]interface{}{
"deleted": true,
"template_id": templateID,
}, nil)
return nil
},
}
113 changes: 113 additions & 0 deletions shortcuts/mail/mail_template_get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package mail

import (
"context"
"fmt"
"io"
"strings"

"github.com/larksuite/cli/internal/output"
"github.com/larksuite/cli/shortcuts/common"
)

// MailTemplateGet fetches a single email template by ID.
var MailTemplateGet = common.Shortcut{
Service: "mail",
Command: "+template-get",
Description: "Get a specific email template by ID, including subject, body and default recipients.",
Risk: "read",
Scopes: []string{"mail:user_mailbox.message:readonly"},
AuthTypes: []string{"user"},
HasFormat: true,
Flags: []common.Flag{
{Name: "template-id", Desc: "Required. Template ID", Required: true},
{Name: "mailbox", Default: "me", Desc: "Mailbox ID or email address (default: me)"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if strings.TrimSpace(runtime.Str("template-id")) == "" {
return output.ErrValidation("--template-id is required")
}
return nil
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
mailboxID := resolveMailboxID(runtime)
templateID := runtime.Str("template-id")
return common.NewDryRunAPI().
Desc("Get email template details").
GET(mailboxPath(mailboxID, "templates", templateID))
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
mailboxID := resolveMailboxID(runtime)
templateID := runtime.Str("template-id")
data, err := runtime.CallAPI("GET", mailboxPath(mailboxID, "templates", templateID), nil, nil)
Comment on lines +29 to +45
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Normalize --template-id before building request paths.

Validation trims --template-id, but DryRun and Execute use the raw flag value. Inputs with surrounding spaces can pass validation yet hit a different API path and fail as “not found”.

💡 Suggested fix
 DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
 	mailboxID := resolveMailboxID(runtime)
-	templateID := runtime.Str("template-id")
+	templateID := strings.TrimSpace(runtime.Str("template-id"))
 	return common.NewDryRunAPI().
 		Desc("Get email template details").
 		GET(mailboxPath(mailboxID, "templates", templateID))
 },
 Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
 	mailboxID := resolveMailboxID(runtime)
-	templateID := runtime.Str("template-id")
+	templateID := strings.TrimSpace(runtime.Str("template-id"))
 	data, err := runtime.CallAPI("GET", mailboxPath(mailboxID, "templates", templateID), nil, nil)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/mail/mail_template_get.go` around lines 29 - 45, Validation trims
the "--template-id" but DryRun and Execute call runtime.Str("template-id")
directly, causing mismatched paths; update DryRun and Execute to use a
normalized templateID (e.g., templateID :=
strings.TrimSpace(runtime.Str("template-id"))) before calling mailboxPath or
runtime.CallAPI so the same trimmed value used in Validate is used to build the
request path (refer to the Validate, DryRun, Execute functions, runtime.Str,
resolveMailboxID, and mailboxPath symbols).

if err != nil {
return output.Errorf(output.ExitAPI, "api_error", "get template failed: %s", err)
}
tmpl := extractTemplateObject(data)
if tmpl == nil {
return output.Errorf(output.ExitAPI, "api_error", "template %s not found", templateID)
}
runtime.OutFormat(tmpl, nil, func(w io.Writer) {
fmt.Fprintf(w, "Template: %s\n", strVal(tmpl["name"]))
fmt.Fprintf(w, "Subject: %s\n", strVal(tmpl["subject"]))
fmt.Fprintf(w, "ID: %s\n", strVal(tmpl["template_id"]))
if to := tmpl["tos"]; to != nil {
fmt.Fprintf(w, "To: %s\n", describeAddressField(to))
}
if cc := tmpl["ccs"]; cc != nil {
fmt.Fprintf(w, "Cc: %s\n", describeAddressField(cc))
}
if bcc := tmpl["bccs"]; bcc != nil {
fmt.Fprintf(w, "Bcc: %s\n", describeAddressField(bcc))
}
})
return nil
},
}

// extractTemplateObject returns the "template" field from an API response,
// tolerating responses that already flattened the object at the top level.
func extractTemplateObject(data map[string]interface{}) map[string]interface{} {
if data == nil {
return nil
}
if tmpl, ok := data["template"].(map[string]interface{}); ok {
return tmpl
}
if _, hasID := data["template_id"]; hasID {
return data
}
return nil
}

// describeAddressField renders a template address list for pretty output.
// It accepts []interface{} of {mail_address,name} maps or a plain string.
func describeAddressField(v interface{}) string {
switch t := v.(type) {
case string:
return t
case []interface{}:
parts := make([]string, 0, len(t))
for _, item := range t {
m, ok := item.(map[string]interface{})
if !ok {
continue
}
email := strVal(m["mail_address"])
if email == "" {
email = strVal(m["email"])
}
name := strVal(m["name"])
if name != "" {
parts = append(parts, fmt.Sprintf("%s <%s>", name, email))
} else if email != "" {
parts = append(parts, email)
}
}
return strings.Join(parts, ", ")
}
return ""
}
80 changes: 80 additions & 0 deletions shortcuts/mail/mail_template_list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package mail

import (
"context"
"fmt"
"io"

"github.com/larksuite/cli/internal/output"
"github.com/larksuite/cli/shortcuts/common"
)

// MailTemplateList lists all email templates in the specified mailbox.
var MailTemplateList = common.Shortcut{
Service: "mail",
Command: "+template-list",
Description: "List all email templates in the current mailbox. Returns template_id, name, subject and create_time for each template.",
Risk: "read",
Scopes: []string{"mail:user_mailbox.message:readonly"},
AuthTypes: []string{"user"},
HasFormat: true,
Flags: []common.Flag{
{Name: "mailbox", Default: "me", Desc: "Mailbox ID or email address (default: me)"},
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
mailboxID := resolveMailboxID(runtime)
return common.NewDryRunAPI().
Desc("List all email templates for the specified mailbox").
GET(mailboxPath(mailboxID, "templates"))
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
mailboxID := resolveMailboxID(runtime)
data, err := runtime.CallAPI("GET", mailboxPath(mailboxID, "templates"), nil, nil)
if err != nil {
return output.Errorf(output.ExitAPI, "api_error", "list templates failed: %s", err)
}
items := extractTemplateList(data)
runtime.OutFormat(map[string]interface{}{"items": items}, &output.Meta{Count: len(items)},
func(w io.Writer) {
if len(items) == 0 {
fmt.Fprintln(w, "No templates found.")
return
}
rows := make([]map[string]interface{}, 0, len(items))
for _, t := range items {
tm, _ := t.(map[string]interface{})
if tm == nil {
continue
}
rows = append(rows, map[string]interface{}{
"template_id": tm["template_id"],
"name": tm["name"],
"subject": common.TruncateStr(fmt.Sprint(tm["subject"]), 40),
"create_time": tm["create_time"],
})
}
output.PrintTable(w, rows)
fmt.Fprintf(w, "\n%d template(s)\n", len(items))
})
return nil
},
}

// extractTemplateList returns the list of templates from an open-apis list response.
// The API uses the "items" field (see tech-design ListUserMailboxTemplateResponse);
// older call sites used "templates", so both are accepted for forward/backward compat.
func extractTemplateList(data map[string]interface{}) []interface{} {
if data == nil {
return nil
}
if list, ok := data["items"].([]interface{}); ok {
return list
}
if list, ok := data["templates"].([]interface{}); ok {
return list
}
return nil
}
Loading
Loading