diff --git a/shortcuts/mail/signature_compose.go b/shortcuts/mail/signature_compose.go
index 6b0519b087..8ccd79a03b 100644
--- a/shortcuts/mail/signature_compose.go
+++ b/shortcuts/mail/signature_compose.go
@@ -18,6 +18,7 @@ import (
draftpkg "github.com/larksuite/cli/shortcuts/mail/draft"
"github.com/larksuite/cli/shortcuts/mail/emlbuilder"
"github.com/larksuite/cli/shortcuts/mail/signature"
+ xhtml "golang.org/x/net/html"
)
// signatureFlag is the common flag definition for --signature-id, shared by all compose shortcuts.
@@ -135,6 +136,7 @@ func resolveSignature(ctx context.Context, runtime *common.RuntimeContext, mailb
Data: data,
})
}
+ rendered = signatureImagesHTML(rendered, images)
}
return &signatureResult{
@@ -144,6 +146,69 @@ func resolveSignature(ctx context.Context, runtime *common.RuntimeContext, mailb
}, nil
}
+// signatureImagesHTML converts editor Drive image sources to MIME CID references.
+// Only downloaded signature images are eligible; unrelated remote images remain
+// untouched. Read and update actual token attributes, never src-looking text
+// inside another attribute. Only changed img tokens are serialized; all other
+// markup is copied verbatim.
+func signatureImagesHTML(content string, images []draftpkg.SignatureImage) string {
+ cids := make(map[string]string, len(images))
+ for _, img := range images {
+ if cid := normalizeInlineCID(img.CID); cid != "" {
+ cids[cid] = cid
+ }
+ }
+ if len(cids) == 0 {
+ return content
+ }
+ var out strings.Builder
+ z := xhtml.NewTokenizer(strings.NewReader(content))
+ for {
+ tt := z.Next()
+ raw := string(z.Raw())
+ if tt == xhtml.ErrorToken {
+ out.WriteString(raw)
+ return out.String()
+ }
+ if tt == xhtml.StartTagToken || tt == xhtml.SelfClosingTagToken {
+ tok := z.Token()
+ if tok.Data == "img" {
+ var src, cid string
+ var srcCount, cidCount int
+ for _, attr := range tok.Attr {
+ switch attr.Key {
+ case "src":
+ srcCount++
+ src = attr.Val
+ case "data-cid":
+ cidCount++
+ cid = normalizeInlineCID(attr.Val)
+ }
+ }
+ // Duplicate image references are ambiguous; preserve the raw token.
+ if srcCount > 1 || cidCount > 1 || strings.HasPrefix(strings.ToLower(strings.TrimSpace(src)), "cid:") {
+ out.WriteString(raw)
+ continue
+ }
+ if cid == "" {
+ if u, err := url.Parse(src); err == nil {
+ cid = normalizeInlineCID(u.Query().Get("cid"))
+ }
+ }
+ if _, ok := cids[cid]; ok {
+ for i := range tok.Attr {
+ if tok.Attr[i].Key == "src" {
+ tok.Attr[i].Val = "cid:" + cid
+ raw = tok.String()
+ }
+ }
+ }
+ }
+ }
+ out.WriteString(raw)
+ }
+}
+
// injectSignatureIntoBody inserts signature HTML into the body, placing
// it right after the user-authored region and before any system-managed
// tail (large attachment card or quote block). Any existing signature is
diff --git a/shortcuts/mail/signature_compose_test.go b/shortcuts/mail/signature_compose_test.go
index 6f6ab936ae..5052b577f2 100644
--- a/shortcuts/mail/signature_compose_test.go
+++ b/shortcuts/mail/signature_compose_test.go
@@ -12,6 +12,7 @@ import (
"testing"
"github.com/spf13/cobra"
+ xhtml "golang.org/x/net/html"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/auth"
@@ -304,6 +305,173 @@ func TestAutoResolveSignatureID_ReturnsReplyID(t *testing.T) {
}
}
+func TestResolveSignature_DriveImageCIDReference(t *testing.T) {
+ const cid = "signature-logo-cid"
+ const imageURL = "https://drive.example.com/image?cid=" + cid + "&token=example"
+ rt, reg := newSigTestRuntime(t)
+ stubSigListResponse(reg, "mbx-drive-image", []map[string]interface{}{{
+ "id": "sig-drive-image", "signature_type": "USER",
+ "content": `
Signature

`,
+ "images": []map[string]interface{}{{
+ "cid": cid, "image_name": "logo.png", "download_url": imageURL,
+ }},
+ }}, nil)
+ rt.Factory.HttpClient = func() (*http.Client, error) {
+ return &http.Client{Transport: signatureRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if req.URL.String() == imageURL {
+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"image/png"}}, Body: io.NopCloser(strings.NewReader("image bytes")), Request: req}, nil
+ }
+ return reg.RoundTrip(req)
+ })}, nil
+ }
+ sig, err := resolveSignature(context.Background(), rt, "mbx-drive-image", "sig-drive-image", "", true, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := injectSignatureIntoBody("Hello
", sig)
+ if err := validateInlineCIDs(body, signatureCIDs(sig), nil); err != nil {
+ t.Fatalf("saved signature image must be referenced by its inline CID: %v", err)
+ }
+ if attrs := signatureImageAttributes(t, body); attrs["src"] != "cid:"+cid {
+ t.Fatalf("expected actual MIME CID source, got attributes %#v", attrs)
+ }
+ if !strings.Contains(body, `data-src="editor-only"`) || !strings.Contains(body, `width="120"`) {
+ t.Fatalf("image metadata must be preserved: %q", body)
+ }
+ bld := emlbuilder.New().From("", "sender@example.com").To("", "recipient@example.com").HTMLBody([]byte(body))
+ raw, err := addSignatureImagesToBuilder(bld, sig).Build()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(strings.ToLower(string(raw)), strings.ToLower("Content-ID: <"+cid+">")) {
+ t.Fatalf("expected matching MIME inline image: %q", raw)
+ }
+}
+
+func TestSignatureImagesHTML(t *testing.T) {
+ images := []draftpkg.SignatureImage{{CID: ""}}
+ for _, tc := range []struct {
+ name, input, want string
+ }{
+ {"data CID", `
`, `
`},
+ {"query CID", `
`, `
`},
+ {"existing CID", `
`, `
`},
+ {"unattached CID", `
`, `
`},
+ {"unrelated remote", `
`, `
`},
+ {"no src", `
`, `
`},
+ {"comment", ``, ``},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := signatureImagesHTML(tc.input, images); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ if got := signatureImagesHTML(tc.input, nil); got != tc.input {
+ t.Fatalf("without downloaded images HTML must be unchanged: %q", got)
+ }
+ })
+ }
+}
+
+// Inspect real HTML attributes: the shared regex CID validator can mistake a
+// src-looking string inside title for an image source.
+func signatureImageAttributes(t *testing.T, content string) map[string]string {
+ t.Helper()
+ z := xhtml.NewTokenizer(strings.NewReader(content))
+ for {
+ tt := z.Next()
+ if tt == xhtml.ErrorToken {
+ t.Fatal("no image found")
+ }
+ if tt != xhtml.StartTagToken && tt != xhtml.SelfClosingTagToken {
+ continue
+ }
+ tok := z.Token()
+ if tok.Data != "img" {
+ continue
+ }
+ attrs := make(map[string]string)
+ for _, attr := range tok.Attr {
+ attrs[attr.Key] = attr.Val
+ }
+ return attrs
+ }
+}
+
+func TestSignatureImagesHTMLQuotedSrcDecoy(t *testing.T) {
+ const prefix = `text
link`
+ const suffix = `

`
+ input := prefix + `
` + suffix
+ got := signatureImagesHTML(input, []draftpkg.SignatureImage{{CID: "logo"}})
+ attrs := signatureImageAttributes(t, got)
+ if attrs["src"] != "cid:logo" {
+ t.Errorf("actual src = %q, want cid:logo; HTML = %s", attrs["src"], got)
+ }
+ if attrs["title"] != " src='decoy'" || attrs["data-cid"] != "logo" {
+ t.Errorf("unrelated attributes changed: %#v", attrs)
+ }
+ if !strings.HasPrefix(got, prefix) || !strings.HasSuffix(got, suffix) {
+ t.Errorf("unrelated markup changed: %s", got)
+ }
+}
+
+func TestSignatureImagesHTMLPreservesExistingCIDWithStaleMetadata(t *testing.T) {
+ for _, src := range []string{"cid:existing", "CID:existing"} {
+ input := `
`
+ got := signatureImagesHTML(input, []draftpkg.SignatureImage{{CID: "logo"}})
+ if got != input {
+ t.Errorf("existing CID must take precedence over stale metadata: got %s, want %s", got, input)
+ }
+ if err := validateInlineCIDs(got, []string{"logo"}, nil); err == nil {
+ t.Error("stale CID conflict must fail validation, not silently remap the image")
+ }
+ }
+}
+
+func TestSignatureImagesHTMLDuplicateSourcePreservesRaw(t *testing.T) {
+ for _, input := range []string{
+ `
`,
+ `
`,
+ `
`,
+ } {
+ got := signatureImagesHTML(input, []draftpkg.SignatureImage{{CID: "logo"}})
+ if got != input {
+ t.Errorf("ambiguous src attributes must remain byte-for-byte unchanged: got %s, want %s", got, input)
+ }
+ if err := validateInlineCIDs(got, []string{"logo"}, nil); err == nil {
+ t.Error("unreferenced signature image must still fail CID validation")
+ }
+ }
+}
+
+func TestSignatureImagesHTMLDuplicateDataCIDPreservesRaw(t *testing.T) {
+ for _, input := range []string{
+ `
`,
+ `
`,
+ `
`,
+ } {
+ got := signatureImagesHTML(input, []draftpkg.SignatureImage{{CID: "logo"}})
+ if got != input {
+ t.Errorf("ambiguous data-cid attributes must remain byte-for-byte unchanged: got %s, want %s", got, input)
+ }
+ if err := validateInlineCIDs(got, []string{"logo"}, nil); err == nil {
+ t.Error("unreferenced signature image must still fail CID validation")
+ }
+ }
+}
+
+func TestSignatureImagesHTMLUnquotedSource(t *testing.T) {
+ for _, input := range []string{
+ `
`,
+ `
`,
+ } {
+ got := signatureImagesHTML(input, []draftpkg.SignatureImage{{CID: "logo"}})
+ attrs := signatureImageAttributes(t, got)
+ if attrs["src"] != "cid:logo" || attrs["width"] != "20" {
+ t.Errorf("unquoted source was not rewritten with metadata preserved: %#v; HTML = %s", attrs, got)
+ }
+ }
+}
+
func TestResolveSignature_EmptyIDReturnsNil(t *testing.T) {
rt, _ := newSigTestRuntime(t)
result, err := resolveSignature(context.Background(), rt, "mbx-empty", "", "user@example.com", false, false)