v1

package
v0.25.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 54 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// The upload memory buffer is 32 MiB.
	// It should be kept low, so RAM usage doesn't get out of control.
	// This is unrelated to maximum upload size limit, which is now set through system setting.
	MaxUploadBufferSizeBytes = 32 << 20
	MebiByte                 = 1024 * 1024
	// ThumbnailCacheFolder is the folder name where the thumbnail images are stored.
	ThumbnailCacheFolder = ".thumbnail_cache"
)
View Source
const (
	// Issuer is the issuer claim in JWT tokens.
	// This identifies tokens as issued by Memos.
	Issuer = "memos"

	// KeyID is the key identifier used in JWT header.
	// Version "v1" allows for future key rotation while maintaining backward compatibility.
	// If signing mechanism changes, add "v2", "v3", etc. and verify both versions.
	KeyID = "v1"

	// AccessTokenAudienceName is the audience claim for JWT access tokens.
	// This ensures tokens are only used for API access, not other purposes.
	AccessTokenAudienceName = "user.access-token"

	// SessionSlidingDuration is the sliding expiration duration for user sessions.
	// Sessions remain valid if accessed within the last 14 days.
	// Each API call extends the session by updating last_accessed_time.
	SessionSlidingDuration = 14 * 24 * time.Hour

	// SessionCookieName is the HTTP cookie name used to store session information.
	// Cookie value format: {userID}-{sessionID}.
	SessionCookieName = "user_session"
)
View Source
const (
	// DefaultPageSize is the default page size for requests.
	DefaultPageSize = 10
	// MaxPageSize is the maximum page size for requests.
	MaxPageSize = 1000
)
View Source
const (
	InstanceSettingNamePrefix  = "instance/settings/"
	UserNamePrefix             = "users/"
	MemoNamePrefix             = "memos/"
	AttachmentNamePrefix       = "attachments/"
	ReactionNamePrefix         = "reactions/"
	InboxNamePrefix            = "inboxes/"
	IdentityProviderNamePrefix = "identity-providers/"
	ActivityNamePrefix         = "activities/"
	WebhookNamePrefix          = "webhooks/"
)

Variables

View Source
var SupportedThumbnailMimeTypes = []string{
	"image/png",
	"image/jpeg",
}

Functions

func BuildSessionCookieValue added in v0.25.0

func BuildSessionCookieValue(userID int32, sessionID string) string

BuildSessionCookieValue creates the session cookie value.

Format: {userID}-{sessionID} Example: "123-550e8400-e29b-41d4-a716-446655440000"

This format allows quick extraction of both user ID and session ID from the cookie without database lookup during authentication.

func ExtractActivityIDFromName added in v0.22.5

func ExtractActivityIDFromName(name string) (int32, error)

func ExtractAttachmentUIDFromName added in v0.25.0

func ExtractAttachmentUIDFromName(name string) (string, error)

ExtractAttachmentUIDFromName returns the attachment UID from a resource name.

func ExtractIdentityProviderIDFromName

func ExtractIdentityProviderIDFromName(name string) (int32, error)

func ExtractInboxIDFromName

func ExtractInboxIDFromName(name string) (int32, error)

ExtractInboxIDFromName returns the inbox ID from a resource name.

func ExtractInstanceSettingKeyFromName added in v0.25.3

func ExtractInstanceSettingKeyFromName(name string) (string, error)

func ExtractMemoUIDFromName added in v0.24.0

func ExtractMemoUIDFromName(name string) (string, error)

ExtractMemoUIDFromName returns the memo UID from a resource name. e.g., "memos/uuid" -> "uuid".

func ExtractNotificationIDFromName added in v0.25.3

func ExtractNotificationIDFromName(name string) (int32, error)

ExtractNotificationIDFromName extracts the notification ID from a resource name. Expected format: users/{user_id}/notifications/{notification_id}.

func ExtractReactionIDFromName added in v0.25.0

func ExtractReactionIDFromName(name string) (int32, error)

ExtractReactionIDFromName returns the reaction ID from a resource name. e.g., "reactions/123" -> 123.

func ExtractUserIDAndSettingKeyFromName added in v0.25.1

func ExtractUserIDAndSettingKeyFromName(name string) (int32, string, error)

ExtractUserIDAndSettingKeyFromName extracts user ID and setting key from resource name. e.g., "users/123/settings/general" -> 123, "general".

func ExtractUserIDFromName

func ExtractUserIDFromName(name string) (int32, error)

ExtractUserIDFromName returns the uid from a resource name.

func GenerateAccessToken

func GenerateAccessToken(username string, userID int32, expirationTime time.Time, secret []byte) (string, error)

GenerateAccessToken generates a JWT access token for a user.

Parameters: - username: The user's username (stored in "name" claim) - userID: The user's ID (stored in "sub" claim) - expirationTime: When the token expires (pass zero time for no expiration) - secret: Server secret used to sign the token

Returns a signed JWT string or an error.

func GenerateSessionID added in v0.25.0

func GenerateSessionID() (string, error)

GenerateSessionID generates a unique session ID.

Uses UUID v4 (random) for high entropy and uniqueness. Session IDs are stored in user settings and used to identify browser sessions.

func GetNameParentTokens

func GetNameParentTokens(name string, tokenPrefixes ...string) ([]string, error)

GetNameParentTokens returns the tokens from a resource name.

func ParseSessionCookieValue added in v0.25.0

func ParseSessionCookieValue(cookieValue string) (int32, string, error)

ParseSessionCookieValue extracts user ID and session ID from cookie value.

Input format: "{userID}-{sessionID}" Returns: (userID, sessionID, error)

Example: "123-550e8400-..." → (123, "550e8400-...", nil).

func SaveAttachmentBlob added in v0.25.0

func SaveAttachmentBlob(ctx context.Context, profile *profile.Profile, stores *store.Store, create *store.Attachment) error

SaveAttachmentBlob save the blob of attachment based on the storage config.

Types

type APIV1Service

func NewAPIV1Service

func NewAPIV1Service(secret string, profile *profile.Profile, store *store.Store, grpcServer *grpc.Server) *APIV1Service

func (*APIV1Service) Check added in v0.24.2

func (*APIV1Service) CreateAttachment added in v0.25.0

func (s *APIV1Service) CreateAttachment(ctx context.Context, request *v1pb.CreateAttachmentRequest) (*v1pb.Attachment, error)

func (*APIV1Service) CreateIdentityProvider

func (s *APIV1Service) CreateIdentityProvider(ctx context.Context, request *v1pb.CreateIdentityProviderRequest) (*v1pb.IdentityProvider, error)

func (*APIV1Service) CreateMemo

func (s *APIV1Service) CreateMemo(ctx context.Context, request *v1pb.CreateMemoRequest) (*v1pb.Memo, error)

func (*APIV1Service) CreateMemoComment

func (s *APIV1Service) CreateMemoComment(ctx context.Context, request *v1pb.CreateMemoCommentRequest) (*v1pb.Memo, error)

func (*APIV1Service) CreateSession added in v0.25.0

CreateSession authenticates a user and establishes a new session.

This endpoint supports two authentication methods: 1. Password-based authentication (username + password) 2. SSO authentication (OAuth2 authorization code)

On successful authentication: - A session cookie is set for web browsers (cookie: user_session={userID}-{sessionID}) - Session information is stored including client details (IP, user agent, device type) - Sessions use sliding expiration: 14 days from last access

Authentication: Not required (public endpoint) Returns: Authenticated user information and last accessed timestamp.

func (*APIV1Service) CreateShortcut added in v0.24.0

func (s *APIV1Service) CreateShortcut(ctx context.Context, request *v1pb.CreateShortcutRequest) (*v1pb.Shortcut, error)

func (*APIV1Service) CreateUser

func (s *APIV1Service) CreateUser(ctx context.Context, request *v1pb.CreateUserRequest) (*v1pb.User, error)

func (*APIV1Service) CreateUserAccessToken

func (s *APIV1Service) CreateUserAccessToken(ctx context.Context, request *v1pb.CreateUserAccessTokenRequest) (*v1pb.UserAccessToken, error)

CreateUserAccessToken creates a new Personal Access Token (PAT) for a user.

Use cases: - User manually creates token in settings for mobile app - User creates token for CLI tool - User creates token for third-party integration

Token properties: - JWT format signed with server secret - Contains user ID and username in claims - Optional expiration time (can be never-expiring) - User-provided description for identification

Security considerations: - Full token is only shown ONCE (in this response) - User should copy and store it securely - Token can be revoked by deleting it from settings

Authentication: Required (session cookie or access token) Authorization: User can only create tokens for themselves.

func (*APIV1Service) CreateUserWebhook added in v0.25.1

func (s *APIV1Service) CreateUserWebhook(ctx context.Context, request *v1pb.CreateUserWebhookRequest) (*v1pb.UserWebhook, error)

func (*APIV1Service) DeleteAttachment added in v0.25.0

func (s *APIV1Service) DeleteAttachment(ctx context.Context, request *v1pb.DeleteAttachmentRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteIdentityProvider

func (s *APIV1Service) DeleteIdentityProvider(ctx context.Context, request *v1pb.DeleteIdentityProviderRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteMemo

func (s *APIV1Service) DeleteMemo(ctx context.Context, request *v1pb.DeleteMemoRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteMemoReaction

func (s *APIV1Service) DeleteMemoReaction(ctx context.Context, request *v1pb.DeleteMemoReactionRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteSession added in v0.25.0

func (s *APIV1Service) DeleteSession(ctx context.Context, _ *v1pb.DeleteSessionRequest) (*emptypb.Empty, error)

DeleteSession terminates the current user session (logout).

This endpoint: 1. Removes the session from the user's sessions list in the database 2. Clears the session cookie by setting it to expire immediately

Authentication: Required (session cookie or access token) Returns: Empty response on success.

func (*APIV1Service) DeleteShortcut added in v0.24.0

func (s *APIV1Service) DeleteShortcut(ctx context.Context, request *v1pb.DeleteShortcutRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteUser

func (s *APIV1Service) DeleteUser(ctx context.Context, request *v1pb.DeleteUserRequest) (*emptypb.Empty, error)

func (*APIV1Service) DeleteUserAccessToken

func (s *APIV1Service) DeleteUserAccessToken(ctx context.Context, request *v1pb.DeleteUserAccessTokenRequest) (*emptypb.Empty, error)

DeleteUserAccessToken revokes a Personal Access Token.

This endpoint: 1. Removes the token from the user's access tokens list 2. Immediately invalidates the token (subsequent API calls with it will fail)

Use cases: - User revokes a compromised token - User removes token for unused app/device - User cleans up old tokens

Authentication: Required (session cookie or access token) Authorization: User can only delete their own tokens.

func (*APIV1Service) DeleteUserNotification added in v0.25.3

func (s *APIV1Service) DeleteUserNotification(ctx context.Context, request *v1pb.DeleteUserNotificationRequest) (*emptypb.Empty, error)

DeleteUserNotification permanently deletes a notification. Only the notification owner can delete their notifications.

func (*APIV1Service) DeleteUserWebhook added in v0.25.1

func (s *APIV1Service) DeleteUserWebhook(ctx context.Context, request *v1pb.DeleteUserWebhookRequest) (*emptypb.Empty, error)

func (*APIV1Service) DispatchMemoCreatedWebhook

func (s *APIV1Service) DispatchMemoCreatedWebhook(ctx context.Context, memo *v1pb.Memo) error

DispatchMemoCreatedWebhook dispatches webhook when memo is created.

func (*APIV1Service) DispatchMemoDeletedWebhook

func (s *APIV1Service) DispatchMemoDeletedWebhook(ctx context.Context, memo *v1pb.Memo) error

DispatchMemoDeletedWebhook dispatches webhook when memo is deleted.

func (*APIV1Service) DispatchMemoUpdatedWebhook

func (s *APIV1Service) DispatchMemoUpdatedWebhook(ctx context.Context, memo *v1pb.Memo) error

DispatchMemoUpdatedWebhook dispatches webhook when memo is updated.

func (*APIV1Service) GetActivity

func (s *APIV1Service) GetActivity(ctx context.Context, request *v1pb.GetActivityRequest) (*v1pb.Activity, error)

func (*APIV1Service) GetAttachment added in v0.25.0

func (s *APIV1Service) GetAttachment(ctx context.Context, request *v1pb.GetAttachmentRequest) (*v1pb.Attachment, error)

func (*APIV1Service) GetAttachmentBinary added in v0.25.0

func (s *APIV1Service) GetAttachmentBinary(ctx context.Context, request *v1pb.GetAttachmentBinaryRequest) (*httpbody.HttpBody, error)

func (*APIV1Service) GetAttachmentBlob added in v0.25.0

func (s *APIV1Service) GetAttachmentBlob(attachment *store.Attachment) ([]byte, error)

func (*APIV1Service) GetCurrentSession added in v0.25.0

GetCurrentSession retrieves the current authenticated session information.

This endpoint is used to: - Check if a user is currently authenticated - Get the current user's information - Retrieve the last accessed time of the session

Authentication: Required (session cookie or access token) Returns: User information and last accessed timestamp.

func (*APIV1Service) GetCurrentUser added in v0.22.1

func (s *APIV1Service) GetCurrentUser(ctx context.Context) (*store.User, error)

func (*APIV1Service) GetIdentityProvider

func (s *APIV1Service) GetIdentityProvider(ctx context.Context, request *v1pb.GetIdentityProviderRequest) (*v1pb.IdentityProvider, error)

func (*APIV1Service) GetInstanceOwner

func (s *APIV1Service) GetInstanceOwner(ctx context.Context) (*v1pb.User, error)

func (*APIV1Service) GetInstanceProfile added in v0.25.3

GetInstanceProfile returns the instance profile.

func (*APIV1Service) GetInstanceSetting added in v0.25.3

func (s *APIV1Service) GetInstanceSetting(ctx context.Context, request *v1pb.GetInstanceSettingRequest) (*v1pb.InstanceSetting, error)

func (*APIV1Service) GetMemo

func (s *APIV1Service) GetMemo(ctx context.Context, request *v1pb.GetMemoRequest) (*v1pb.Memo, error)

func (*APIV1Service) GetShortcut added in v0.25.0

func (s *APIV1Service) GetShortcut(ctx context.Context, request *v1pb.GetShortcutRequest) (*v1pb.Shortcut, error)

func (*APIV1Service) GetUser

func (s *APIV1Service) GetUser(ctx context.Context, request *v1pb.GetUserRequest) (*v1pb.User, error)

func (*APIV1Service) GetUserAvatar added in v0.25.0

func (s *APIV1Service) GetUserAvatar(ctx context.Context, request *v1pb.GetUserAvatarRequest) (*httpbody.HttpBody, error)

func (*APIV1Service) GetUserSetting

func (s *APIV1Service) GetUserSetting(ctx context.Context, request *v1pb.GetUserSettingRequest) (*v1pb.UserSetting, error)

func (*APIV1Service) GetUserStats added in v0.23.1

func (s *APIV1Service) GetUserStats(ctx context.Context, request *v1pb.GetUserStatsRequest) (*v1pb.UserStats, error)

func (*APIV1Service) ListActivities added in v0.25.0

func (*APIV1Service) ListAllUserStats added in v0.23.1

func (*APIV1Service) ListAttachments added in v0.25.0

func (*APIV1Service) ListMemoAttachments added in v0.25.0

func (*APIV1Service) ListMemoComments

func (*APIV1Service) ListMemoReactions

func (*APIV1Service) ListMemoRelations

func (*APIV1Service) ListMemos

func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosRequest) (*v1pb.ListMemosResponse, error)

func (*APIV1Service) ListShortcuts added in v0.24.0

func (*APIV1Service) ListUserAccessTokens

ListUserAccessTokens retrieves all Personal Access Tokens (PATs) for a user.

Personal Access Tokens are used for: - Mobile app authentication - CLI tool authentication - API client authentication - Any programmatic access requiring Bearer token auth

Security: - Only the token owner can list their tokens - Returns full token strings (so users can manage/revoke them) - Invalid or expired tokens are filtered out

Authentication: Required (session cookie or access token) Authorization: User can only list their own tokens.

func (*APIV1Service) ListUserNotifications added in v0.25.3

ListUserNotifications lists all notifications for a user. Notifications are backed by the inbox storage layer and represent activities that require user attention (e.g., memo comments).

func (*APIV1Service) ListUserSessions added in v0.25.0

ListUserSessions retrieves all active sessions for a user.

Sessions represent active browser logins. Each session includes: - session_id: Unique identifier - create_time: When the session was created - last_accessed_time: Last API call time (for sliding expiration) - client_info: Device details (browser, OS, IP address, device type)

Use cases: - User reviews where they're logged in - User identifies suspicious login attempts - User prepares to revoke specific sessions

Authentication: Required (session cookie or access token) Authorization: User can only list their own sessions.

func (*APIV1Service) ListUserSettings added in v0.25.1

func (*APIV1Service) ListUserWebhooks added in v0.25.1

func (*APIV1Service) ListUsers

func (s *APIV1Service) ListUsers(ctx context.Context, request *v1pb.ListUsersRequest) (*v1pb.ListUsersResponse, error)

func (*APIV1Service) RegisterGateway

func (s *APIV1Service) RegisterGateway(ctx context.Context, echoServer *echo.Echo) error

RegisterGateway registers the gRPC-Gateway with the given Echo instance.

func (*APIV1Service) RevokeUserSession added in v0.25.0

func (s *APIV1Service) RevokeUserSession(ctx context.Context, request *v1pb.RevokeUserSessionRequest) (*emptypb.Empty, error)

RevokeUserSession terminates a specific session for a user.

This endpoint: 1. Removes the session from the user's sessions list 2. Immediately invalidates the session 3. Forces the device to re-login on next request

Use cases: - User logs out from a specific device (e.g., "Log out my phone") - User removes suspicious/unknown session - User logs out from all devices except current one

Note: This is different from DeleteSession (logout current session). This endpoint allows revoking ANY session, not just the current one.

Authentication: Required (session cookie or access token) Authorization: User can only revoke their own sessions.

func (*APIV1Service) SetMemoAttachments added in v0.25.0

func (s *APIV1Service) SetMemoAttachments(ctx context.Context, request *v1pb.SetMemoAttachmentsRequest) (*emptypb.Empty, error)

func (*APIV1Service) SetMemoRelations

func (s *APIV1Service) SetMemoRelations(ctx context.Context, request *v1pb.SetMemoRelationsRequest) (*emptypb.Empty, error)

func (*APIV1Service) UpdateAttachment added in v0.25.0

func (s *APIV1Service) UpdateAttachment(ctx context.Context, request *v1pb.UpdateAttachmentRequest) (*v1pb.Attachment, error)

func (*APIV1Service) UpdateIdentityProvider

func (s *APIV1Service) UpdateIdentityProvider(ctx context.Context, request *v1pb.UpdateIdentityProviderRequest) (*v1pb.IdentityProvider, error)

func (*APIV1Service) UpdateInstanceSetting added in v0.25.3

func (s *APIV1Service) UpdateInstanceSetting(ctx context.Context, request *v1pb.UpdateInstanceSettingRequest) (*v1pb.InstanceSetting, error)

func (*APIV1Service) UpdateMemo

func (s *APIV1Service) UpdateMemo(ctx context.Context, request *v1pb.UpdateMemoRequest) (*v1pb.Memo, error)

func (*APIV1Service) UpdateShortcut added in v0.24.0

func (s *APIV1Service) UpdateShortcut(ctx context.Context, request *v1pb.UpdateShortcutRequest) (*v1pb.Shortcut, error)

func (*APIV1Service) UpdateUser

func (s *APIV1Service) UpdateUser(ctx context.Context, request *v1pb.UpdateUserRequest) (*v1pb.User, error)

func (*APIV1Service) UpdateUserNotification added in v0.25.3

func (s *APIV1Service) UpdateUserNotification(ctx context.Context, request *v1pb.UpdateUserNotificationRequest) (*v1pb.UserNotification, error)

UpdateUserNotification updates a notification's status (e.g., marking as read/archived). Only the notification owner can update their notifications.

func (*APIV1Service) UpdateUserSetting

func (s *APIV1Service) UpdateUserSetting(ctx context.Context, request *v1pb.UpdateUserSettingRequest) (*v1pb.UserSetting, error)

func (*APIV1Service) UpdateUserWebhook added in v0.25.1

func (s *APIV1Service) UpdateUserWebhook(ctx context.Context, request *v1pb.UpdateUserWebhookRequest) (*v1pb.UserWebhook, error)

func (*APIV1Service) UpsertAccessTokenToStore

func (s *APIV1Service) UpsertAccessTokenToStore(ctx context.Context, user *store.User, accessToken, description string) error

func (*APIV1Service) UpsertMemoReaction

func (s *APIV1Service) UpsertMemoReaction(ctx context.Context, request *v1pb.UpsertMemoReactionRequest) (*v1pb.Reaction, error)

func (*APIV1Service) UpsertUserSession added in v0.25.0

func (s *APIV1Service) UpsertUserSession(ctx context.Context, userID int32, sessionID string, clientInfo *storepb.SessionsUserSetting_ClientInfo) error

UpsertUserSession adds or updates a user session.

type ClaimsMessage

type ClaimsMessage struct {
	Name string `json:"name"` // Username
	jwt.RegisteredClaims
}

ClaimsMessage represents the claims structure in a JWT token.

JWT Claims include: - name: Username (custom claim) - iss: Issuer = "memos" - aud: Audience = "user.access-token" - sub: Subject = user ID - iat: Issued at time - exp: Expiration time (optional, may be empty for never-expiring tokens).

type ContextKey

type ContextKey int

ContextKey is the key type of context value.

const (
	// UserIDContextKey stores the authenticated user's ID in the context.
	// Set for both session-based and token-based authentication.
	UserIDContextKey ContextKey = iota
)

type GRPCAuthInterceptor

type GRPCAuthInterceptor struct {
	Store *store.Store
	// contains filtered or unexported fields
}

GRPCAuthInterceptor is the auth interceptor for gRPC server.

func NewGRPCAuthInterceptor

func NewGRPCAuthInterceptor(store *store.Store, secret string) *GRPCAuthInterceptor

NewGRPCAuthInterceptor returns a new API auth interceptor.

func (*GRPCAuthInterceptor) AuthenticationInterceptor

func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error)

AuthenticationInterceptor is the unary interceptor for gRPC API.

Authentication Strategy (in priority order): 1. Session Cookie: Check for "user_session" cookie with format "{userID}-{sessionID}" 2. Access Token: Check for "Authorization: Bearer {token}" header with JWT 3. Public Endpoints: Allow if method is in public allowlist 4. Reject: Return 401 Unauthenticated if none of the above succeed

On successful authentication, sets context values: - UserIDContextKey: The authenticated user's ID (always set) - sessionIDContextKey: Session ID (only for cookie auth) - accessTokenContextKey: JWT token (only for Bearer token auth).

type LoggerInterceptor

type LoggerInterceptor struct {
	// contains filtered or unexported fields
}

func NewLoggerInterceptor

func NewLoggerInterceptor(logStacktrace bool) *LoggerInterceptor

func (*LoggerInterceptor) LoggerInterceptor

func (in *LoggerInterceptor) LoggerInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL