mirror of
https://github.com/larksuite/cli.git
synced 2026-07-09 02:14:02 +08:00
Add strongly-typed shortcut protocol that coexists with the legacy
common.Shortcut. The new common.TypedShortcut[T] is a generic outer
wrapper backed by a reflect-driven binder; both legacy and typed
shortcuts satisfy a new common.Mountable / common.ShortcutDescriptor
interface pair so register.go can dispatch either through the same
pipeline.
Framework (shortcuts/common):
- protocol.go — Mountable / ShortcutDescriptor / OneOfMarker /
Validatable / Normalizable[T] / ArgsValidator / Maybe[T] /
HelpExample
- binder.go — reflect Args walk, intra-Args flag-tag uniqueness
panic, cobra flag registration, bindFlags + bindMaybe, runNormalize
(via MethodByName dispatch — Normalizable[T] can't be type-asserted
through a non-generic interface), runValidateValue, runFrameworkRules
for required / enum / OneOf / group
- typed_shortcut.go — TypedShortcut[T] struct, 8 descriptor methods,
mountTyped adapter that synthesizes a legacy Shortcut shell and
reuses runShortcut verbatim (identity / scopes / @file / stdin / jq
/ dry-run / high-risk gate)
- typed_help.go — sectioned --help (CHOOSE ONE / OPTIONAL / EXAMPLES)
with cmdutil.GetRisk/GetTips passthrough so typed shortcuts keep the
Risk: and Tips: blocks
- runner.go — typedArgs lifecycle slot on RuntimeContext
- types.go — 5 GetX accessors on *Shortcut so legacy shortcuts
satisfy ShortcutDescriptor alongside the existing pointer-receiver
scope methods
Typed primitives (shortcuts/common/argstype):
- ChatID / UserOpenID / UserOpenIDList — prefix-validated identifiers
- SafePath — cwd-relative, rejects absolute paths and ".." segments
- MediaInput — tri-state (URL bypass / img_xxx-file_xxx key bypass /
SafePath delegation)
- SpreadsheetRef — Normalize extracts shtcn token from feishu URLs
Error contract (errs):
- 3 new Subtype constants: shortcut_oneof_missing /
shortcut_oneof_multiple / shortcut_group_incomplete. Per-field
failures (required / enum / typed primitive format) reuse the
existing SubtypeInvalidArgument so no new error type is introduced.
Registry refactor (shortcuts + cmd):
- AllShortcuts() now returns []common.ShortcutDescriptor; legacy
shortcuts are boxed as *Shortcut (pointer required for the
pointer-receiver scope methods), typed shortcuts boxed as Mountable
- Register dispatches via the Mountable interface
- cmd/auth/login, cmd/auth/login_interactive, cmd/error_auth_hint,
cmd/diagnose_scope_test, shortcuts/register_test (shortcuts.json
generator) updated to read through GetService / GetCommand /
GetAuthTypes / GetDescription / DeclaredScopesForIdentity
- shortcutSupportsIdentity helpers accept ShortcutDescriptor
Pilot (shortcuts/im):
- protocol.go — MessageTarget / MessageContent (with seven content
variants) / VideoContent (paired video + cover) / RawContent
(--content with explicit msg-type, validates JSON in
ValidateValue)
- im_messages_send.go — migrated to TypedShortcut[*ImMessagesSendArgs].
Inline Validate closure is replaced by framework-derived checks
(OneOf target, OneOf content, VideoContent group, typed-primitive
formats, RawContent JSON). Helpers (resolveMediaContent,
wrapMarkdownAsPostForDryRun, normalizeAtMentions, etc.) reused
verbatim; only the field-access pattern changes from
runtime.Str("x") to args.X.
- shortcuts.go — new TypedShortcuts() exporter; ImMessagesSend
removed from the legacy Shortcuts() slice so it is not
double-mounted
- register.go wires addTyped(im.TypedShortcuts()) into init
Known follow-ups:
- runFrameworkRules and bindFlags do not recurse into OneOf bucket /
group sub-structs; im messages-send compensates with a local
bindMessagesSendArgs + validateVideoGroup. Generalizing the binder
to recurse will let future migrations drop the local shim.
- common.ValidateChatID / common.ValidateUserID become redundant
once all legacy shortcuts that call them migrate; can be retired
with the last legacy caller.
Refs: docs/superpowers/specs/2026-05-26-shortcut-protocol-design.md
215 lines
6.8 KiB
Go
215 lines
6.8 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package cmd
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/larksuite/cli/errs"
|
|
internalauth "github.com/larksuite/cli/internal/auth"
|
|
"github.com/larksuite/cli/internal/cmdutil"
|
|
"github.com/larksuite/cli/internal/core"
|
|
"github.com/larksuite/cli/internal/output"
|
|
"github.com/larksuite/cli/internal/registry"
|
|
"github.com/larksuite/cli/shortcuts"
|
|
shortcutcommon "github.com/larksuite/cli/shortcuts/common"
|
|
)
|
|
|
|
// applyNeedAuthorizationHint augments a typed *errs.AuthenticationError with a
|
|
// "current command requires scope(s): X, Y" hint when the underlying error is
|
|
// a need_user_authorization signal AND the current command declares scopes
|
|
// locally (via shortcut registration or service-method metadata).
|
|
//
|
|
// Stage-1: this typed path is dormant — no production code returns a typed
|
|
// *errs.AuthenticationError. Kept so per-domain stage-2 migrations can plug
|
|
// in without re-architecting. The active stage-1 path is
|
|
// enrichMissingScopeError below, which operates on legacy *output.ExitError.
|
|
func applyNeedAuthorizationHint(f *cmdutil.Factory, err error) {
|
|
if err == nil || f == nil {
|
|
return
|
|
}
|
|
if !internalauth.IsNeedUserAuthorizationError(err) {
|
|
return
|
|
}
|
|
var authErr *errs.AuthenticationError
|
|
if !errors.As(err, &authErr) {
|
|
return
|
|
}
|
|
scopes := resolveDeclaredScopesForCurrentCommand(f)
|
|
if len(scopes) == 0 {
|
|
return
|
|
}
|
|
scopeHint := fmt.Sprintf("current command requires scope(s): %s", strings.Join(scopes, ", "))
|
|
if authErr.Hint == "" {
|
|
authErr.Hint = scopeHint
|
|
return
|
|
}
|
|
authErr.Hint += "\n" + scopeHint
|
|
}
|
|
|
|
// enrichMissingScopeError appends a "current command requires scope(s): X"
|
|
// hint to a legacy *output.ExitError when the underlying error carries the
|
|
// need_user_authorization marker AND the current command declares scopes
|
|
// locally. Matches pre-PR behaviour byte-for-byte; lives on the legacy
|
|
// envelope path until per-domain stage-2 typed migration.
|
|
//
|
|
// Deprecated: stage-1 enrichment for the legacy *output.ExitError surface.
|
|
// Stage-2 typed migration will lift this into AuthenticationError.Hint on
|
|
// the typed envelope via applyNeedAuthorizationHint and remove this helper.
|
|
func enrichMissingScopeError(f *cmdutil.Factory, exitErr *output.ExitError) {
|
|
if exitErr == nil || exitErr.Detail == nil {
|
|
return
|
|
}
|
|
if !internalauth.IsNeedUserAuthorizationError(exitErr) {
|
|
return
|
|
}
|
|
scopes := resolveDeclaredScopesForCurrentCommand(f)
|
|
if len(scopes) == 0 {
|
|
return
|
|
}
|
|
scopeHint := fmt.Sprintf("current command requires scope(s): %s", strings.Join(scopes, ", "))
|
|
if exitErr.Detail.Hint == "" {
|
|
exitErr.Detail.Hint = scopeHint
|
|
return
|
|
}
|
|
exitErr.Detail.Hint += "\n" + scopeHint
|
|
}
|
|
|
|
// resolveDeclaredScopesForCurrentCommand returns the scopes declared by the
|
|
// current command for the resolved identity, checking shortcuts first and then
|
|
// service methods from local registry metadata.
|
|
func resolveDeclaredScopesForCurrentCommand(f *cmdutil.Factory) []string {
|
|
if f == nil || f.CurrentCommand == nil {
|
|
return nil
|
|
}
|
|
|
|
identity := string(f.ResolvedIdentity)
|
|
if identity == "" {
|
|
identity = string(core.AsUser)
|
|
}
|
|
if identity != string(core.AsUser) && identity != string(core.AsBot) {
|
|
return nil
|
|
}
|
|
|
|
if scopes := resolveDeclaredShortcutScopes(f.CurrentCommand, identity); len(scopes) > 0 {
|
|
return scopes
|
|
}
|
|
return resolveDeclaredServiceMethodScopes(f.CurrentCommand, identity)
|
|
}
|
|
|
|
// resolveDeclaredShortcutScopes returns the scopes declared by a mounted
|
|
// shortcut command for the given identity.
|
|
func resolveDeclaredShortcutScopes(cmd *cobra.Command, identity string) []string {
|
|
if cmd == nil || cmd.Parent() == nil || !strings.HasPrefix(cmd.Name(), "+") {
|
|
return nil
|
|
}
|
|
|
|
service := cmd.Parent().Name()
|
|
for _, sc := range shortcuts.AllShortcuts() {
|
|
if sc.GetService() != service || sc.GetCommand() != cmd.Name() || !shortcutSupportsIdentity(sc, identity) {
|
|
continue
|
|
}
|
|
scopes := sc.DeclaredScopesForIdentity(identity)
|
|
if len(scopes) == 0 {
|
|
return nil
|
|
}
|
|
return append([]string(nil), scopes...)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveDeclaredServiceMethodScopes returns the scopes declared by a
|
|
// service/resource/method command from the embedded from_meta registry.
|
|
func resolveDeclaredServiceMethodScopes(cmd *cobra.Command, identity string) []string {
|
|
// Service-method scope lookup only applies to commands mounted as
|
|
// root -> service -> resource -> method. Non-resource/method commands
|
|
// intentionally return no scopes here so auth-hint enrichment does not
|
|
// change runtime semantics for other command shapes.
|
|
if cmd == nil || cmd.Parent() == nil || cmd.Parent().Parent() == nil || cmd.Parent().Parent().Parent() == nil {
|
|
return nil
|
|
}
|
|
if strings.HasPrefix(cmd.Name(), "+") {
|
|
return nil
|
|
}
|
|
|
|
service := cmd.Parent().Parent().Name()
|
|
resource := cmd.Parent().Name()
|
|
method := cmd.Name()
|
|
|
|
spec := registry.LoadFromMeta(service)
|
|
if spec == nil {
|
|
return nil
|
|
}
|
|
resources, _ := spec["resources"].(map[string]interface{})
|
|
resMap, _ := resources[resource].(map[string]interface{})
|
|
if resMap == nil {
|
|
return nil
|
|
}
|
|
methods, _ := resMap["methods"].(map[string]interface{})
|
|
methodMap, _ := methods[method].(map[string]interface{})
|
|
if methodMap == nil {
|
|
return nil
|
|
}
|
|
return declaredScopesForMethod(methodMap, identity)
|
|
}
|
|
|
|
// declaredScopesForMethod returns all requiredScopes when present; otherwise it
|
|
// resolves the single recommended scope from the method's scopes list.
|
|
func declaredScopesForMethod(method map[string]interface{}, identity string) []string {
|
|
if requiredRaw, ok := method["requiredScopes"].([]interface{}); ok && len(requiredRaw) > 0 {
|
|
return interfaceStrings(requiredRaw)
|
|
}
|
|
|
|
rawScopes, _ := method["scopes"].([]interface{})
|
|
if len(rawScopes) == 0 {
|
|
return nil
|
|
}
|
|
recommended := registry.SelectRecommendedScope(rawScopes, identity)
|
|
if recommended == "" {
|
|
for _, raw := range rawScopes {
|
|
if scope, ok := raw.(string); ok && scope != "" {
|
|
recommended = scope
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if recommended == "" {
|
|
return nil
|
|
}
|
|
return []string{recommended}
|
|
}
|
|
|
|
// interfaceStrings converts a []interface{} containing strings into a compact
|
|
// []string, skipping empty or non-string values.
|
|
func interfaceStrings(values []interface{}) []string {
|
|
scopes := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
scope, ok := value.(string)
|
|
if !ok || scope == "" {
|
|
continue
|
|
}
|
|
scopes = append(scopes, scope)
|
|
}
|
|
return scopes
|
|
}
|
|
|
|
// shortcutSupportsIdentity reports whether a shortcut supports the requested
|
|
// identity, applying the default user-only behavior when AuthTypes is empty.
|
|
func shortcutSupportsIdentity(sc shortcutcommon.ShortcutDescriptor, identity string) bool {
|
|
authTypes := sc.GetAuthTypes()
|
|
if len(authTypes) == 0 {
|
|
authTypes = []string{string(core.AsUser)}
|
|
}
|
|
for _, authType := range authTypes {
|
|
if authType == identity {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|