whatsapp

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 42 Imported by: 0

README

Arandu

Arandu WhatsApp

WhatsApp API module for Arandu applications. It provides instance management, pairing, messaging, contacts, groups, media downloads and outbound webhooks on top of whatsmeow.

The module uses Arandu sessions and Grants, typed configuration, host-owned database handles and Foundation migrations. It does not read environment variables or open a second application database.

Requirements

  • Go 1.26.10 or newer.
  • Arandu Framework 0.66 or newer.
  • PostgreSQL or SQLite with foreign keys enabled.
  • ffmpeg and ffprobe for audio and thumbnail processing.

Install

go get github.com/hyz-is/arandu-whatsapp

Wire it

An Arandu application registers a module explicitly. There is no service provider, no container and no discovery, so the base wiring stays visible in bootstrap/app.go. The optional documentation wiring is shown separately below.

The import, with the other module imports:

import (
	"github.com/arandu-io/framework/security"
	whatsapp "github.com/hyz-is/arandu-whatsapp"
)

The construction, in Build, after the session store exists and before k.Register:

	whatsappModule, err := whatsapp.New(whatsapp.Config{
		Tenant: cfg.Auth.Tenant,
		Webhooks: whatsapp.WebhookConfig{
			SigningSecret: cfg.WhatsApp.WebhookSigningSecret,
		},
		Policy: whatsapp.PolicyConfig{
			Roles: map[security.Action][]string{
				whatsapp.ActionInstanceCreate: {"admin"},
				whatsapp.ActionInstanceList:   {"admin", "operator"},
				whatsapp.ActionInstanceView:   {"admin", "operator"},
				whatsapp.ActionConnectionPair: {"admin", "operator"},
				whatsapp.ActionMessageSend:    {"admin", "operator"},
			},
		},
	}, db, sessions)
	if err != nil {
		return App{}, err
	}

And the registration, inside the k.Register(...) call already there:

		whatsappModule,

Webhook delivery and mention-all sends use the application's native database queue. Keep the module in the generated bootstrap.App so worker processes receive the same explicitly wired instance:

type App struct {
	Kernel   *kernel.Kernel
	WhatsApp *whatsapp.Module
	// ...the generated fields remain here.
}

Include it in Build's return value:

return App{
	Kernel: k,
	WhatsApp: whatsappModule,
	// ...the generated fields remain here.
}, nil

Then pass app.WhatsApp from the "work" branch in bootstrap/console.go:

return work(ctx, k, app.Queue, app.WhatsApp, args)

Finally, adapt the generated functions in bootstrap/background.go:

type jobHandlerRegistrar interface {
	RegisterJobHandlers(*queue.Worker) error
}

func work(ctx context.Context, k *kernel.Kernel, store queue.Queue,
	registrar jobHandlerRegistrar, args []string,
) error {
	flags := flag.NewFlagSet("work", flag.ContinueOnError)
	name := flags.String("queue", jobs.DefaultQueue, "which queue to drain")
	workers := flags.Int("workers", 4, "how many jobs to run at once")
	if err := flags.Parse(args); err != nil {
		return err
	}
	if err := k.Boot(ctx); err != nil {
		return err
	}
	defer func() { _ = k.Shutdown() }()

	w := queue.NewWorker(store, queue.WorkerOptions{
		Queue:       *name,
		Concurrency: *workers,
		Recorder:    k.Recorder(),
	})
	if err := registerHandlers(w, registrar); err != nil {
		return err
	}
	if len(w.Names()) == 0 {
		return fmt.Errorf("no job handlers are registered")
	}

	ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
	defer stop()
	_, err := w.Daemon(ctx)
	return err
}

func registerHandlers(w *queue.Worker, registrar jobHandlerRegistrar) error {
	if err := registrar.RegisterJobHandlers(w); err != nil {
		return err
	}
	// arandu:begin custom
	// Register other application handlers here.
	// arandu:end custom
	return nil
}

This keeps handler registration explicit without a global or discovery hook. The generated queue module supplies the native jobs-table migrations. Add the WhatsApp queue to the queues it monitors, preserving every queue the application already names:

jobs.NewModule(
	queueStore,
	jobs.DefaultQueue,
	whatsapp.WebhookQueueName,
	whatsapp.MessageQueueName,
)

Without those names workers still drain jobs, but native health and diagnostic checks watch only the default queue and cannot report WhatsApp backlog.

Then, once, before the application serves:

aru migrate

Run each dedicated queue in a worker process:

aru queue:work --queue=whatsapp-webhooks --workers=N
aru queue:work --queue=whatsapp-messages --workers=N

The policy is default-deny. Only actions present in Policy.Roles or Policy.Actions are opened; unknown and newly added actions stay closed. Policy.Roles opens an action to subjects with a role; Policy.Actions opens it to subjects that carry that very action, which is how an application whose permission groups are arandu-permission's grants it.

One registration hosts every tenant of the application. Each instance belongs to the tenant of the Grant that created it, and everything it does afterwards -- pairing, reconnecting, persisting inbound events, dispatching webhooks, running queued jobs -- runs under a runtime Grant of that tenant. At boot, Start discovers which tenants have paired instances (the only read that crosses tenants, and it answers tenant identifiers only) and restores each one under its own Grant. Config.Tenant is the guest realm and the tenant that discovery runs under; a subject with no tenant is refused before authorization or SQL.

To be told about inbound messages in process, register a listener before Start:

whatsappModule.OnInbound(func(ctx context.Context, g security.Grant, m whatsapp.InboundMessage) {
	// data.Tenant(g) is the organization the message belongs to.
})

This package declares four ordered Foundation migrations: three reversible package schemas and the upstream WhatsMeow store upgrade. They are exposed through foundation.Migratable, which is why the migration step is not optional and why arandu.mod.toml declares it. New, Boot and Start never apply migrations.

Configuration

field required meaning
Tenant yes guest realm and the tenant boot discovery runs under; the module serves every tenant.
Prefix no where the routes are mounted. Defaults to /whatsapp.
WhatsApp no pairing, device identity, reconnect and address-cache settings.
Persistence no enables persistence of messages, updates and contacts.
Webhooks no signed global/instance delivery, retention and native database queue.
Processing no mention-all operation timeouts and recoverable snapshot retention; worker concurrency belongs to aru queue:work.
Media no limits, temporary directory and ffmpeg/ffprobe paths.
Policy.Roles no roles allowed for each action; empty denies every action.

New returns an error rather than starting half-wired, so a setting that cannot work fails where it is written instead of on the first request that needed it.

Webhooks.SigningSecret must contain at least 32 bytes before a global or instance webhook can be enabled. Every attempt carries X-Arandu-Timestamp and X-Arandu-Signature; the signature is HMAC-SHA256 over timestamp.deliveryId.body. Delivery snapshots default to 30 days of retention and successful snapshots are compacted immediately.

Processing.Retention also defaults to 30 days. A second native job removes an abandoned mention-all snapshot together with its processing job, and an expired processing job is discarded before any WhatsApp access.

HTTP API

The default base path is /whatsapp/instances. The module registers 36 named routes for instances, pairing, connection state, webhooks, messages, contacts, media, chats, calls and groups. Requests authenticate exclusively through the Arandu session store.

When the host installs and enables Arandu Swagger, the exact paths, request bodies, response envelopes and status codes are published from the same named routes that serve requests. Message, Passkey and webhook behavior is documented under docs.

JSON responses use Arandu resources and are wrapped in data. Tenant IDs and the WhatsMeow device-store key are never exposed. Authorization failures use a generic public message; internal policy details stay on the server.

Layout

module.go                         Arandu wiring and lifecycle
contracts.go, errors.go, exports_*.go
                                  stable root package interface
config/whatsapp.go                typed configuration
app/Enums/                        action vocabulary
app/Models/                       entities and shared contracts
app/Policies/                     default-deny authorization
app/Repositories/                 Grant-first persistence facade
app/Services/                     authorized domain rules
app/Http/Requests/                typed request contracts
app/Http/Resources/               explicit response fields
app/Http/Controllers/             thin HTTP adapters
app/Http/Documentation/           native Arandu Swagger contract
app/Jobs/                         durable queue vocabulary
routes/web.go                     canonical named HTTP surface
database/migrations/              ordered Foundation migrations
internal/                         private persistence and WhatsApp runtime

The root aliases preserve the package-skeleton installation contract (whatsapp.New, whatsapp.Config, whatsapp.Service). Implementation packages follow the same responsibility tree as an Arandu application, and none imports the root facade.

What is already correct, and has to stay that way

The policy denies everything by default. An application opens actions with explicit entries in Config.Policy.Roles.

The repository takes (ctx, g, id), in that order. The Grant comes before the identifier so that naming a record without a decision about it is not expressible. Every method opens with g.Check, which proves the Grant was issued for that exact action rather than for another one.

The tenant comes from data.Tenant(g). Never from the path, body, query or header. The service also refuses a subject with no tenant before authorization or SQL.

arandu.mod.toml declares what the package does — network, filesystem, exec, migrations — and aru doctor compares the declaration against the calls found by its capability analysis. A package that performs an outbound request while declaring network = false is rejected.

Lifecycle and ownership

  • New validates and assembles collaborators without I/O or goroutines.
  • Boot configures the process-wide WhatsMeow device descriptor.
  • Start verifies schema state, discovers the tenants with paired instances and restores each tenant's connections under its own Grant, asynchronously. Without the schema it still boots: it logs the error, Available returns ErrSchemaUnavailable, operations are refused and the schema is rechecked until aru migrate has run (see docs/migrations.md).
  • Health checks the borrowed database and connection-restore result.
  • Close stops module-owned work and disconnects managed clients. The host application owns all native queue workers.

The host retains ownership of the database, SQL pool and session store.

Documentation

Documentation is optional and owned by the host application. Build one arandu-swagger module in bootstrap/app.go, using an application setting loaded from configuration or dotenv for Enabled, and register it last:

docs, err := swagger.New(swagger.Config{
	Enabled:  documentationEnabled,
	Title:    "WhatsApp API",
	Version:  "1.0.0",
	UIPath:   "/docs",
	SpecPath: "/docs/openapi.json",
	Filter: swagger.RouteFilter{
		IncludeModules: []string{"whatsapp"},
	},
	UIMiddleware:   []swagger.Middleware{requireDocumentationAccess},
	SpecMiddleware: []swagger.Middleware{requireDocumentationAccess},
})
if err != nil {
	return App{}, err
}

whatsappModule, err := whatsapp.NewWithDocumentation(
	whatsappConfig,
	db,
	sessions,
	docs,
)
if err != nil {
	return App{}, err
}

k.Register(whatsappModule, docs)

Enabled: false registers neither the UI nor the specification route. When enabled, access to the configured UIPath and SpecPath is controlled by the application middleware supplied through UIMiddleware and SpecMiddleware. The package never reads environment variables itself. Applications that do not publish OpenAPI continue to use whatsapp.New unchanged.

Tests

go test -race ./...

The suite includes policy-before-database checks, tenant isolation, migrations through Hesape's migrator, domain-schema rollback and lifecycle ownership.

Licence

MIT. See LICENSE.md.

Copyright (c) HYZIS - SERVICOS DIGITAIS LTDA - EPP

Documentation

Overview

Package whatsapp provides a tenant-scoped WhatsApp API module for Arandu.

Index

Constants

View Source
const (
	PasskeyStateIdle                 = internalwhatsapp.PasskeyStateIdle
	PasskeyStateFetchingChallenge    = internalwhatsapp.PasskeyStateFetchingChallenge
	PasskeyStateAwaitingAssertion    = internalwhatsapp.PasskeyStateAwaitingAssertion
	PasskeyStateSubmittingAssertion  = internalwhatsapp.PasskeyStateSubmittingAssertion
	PasskeyStateAwaitingConfirmation = internalwhatsapp.PasskeyStateAwaitingConfirmation
	PasskeyStateConfirmationSent     = internalwhatsapp.PasskeyStateConfirmationSent
	PasskeyStateCompleted            = internalwhatsapp.PasskeyStateCompleted
	PasskeyStateFailed               = internalwhatsapp.PasskeyStateFailed
	PasskeyStateExpired              = internalwhatsapp.PasskeyStateExpired
)

Passkey pairing states describe the complete pairing lifecycle.

View Source
const (
	DeviceMessageIOS     = dbtypes.DeviceMessageIOS
	DeviceMessageAndroid = dbtypes.DeviceMessageAndroid
	DeviceMessageWeb     = dbtypes.DeviceMessageWeb
	DeviceMessageUnknown = dbtypes.DeviceMessageUnknown
	DeviceMessageDesktop = dbtypes.DeviceMessageDesktop
)

Device message values identify supported WhatsApp client classes.

View Source
const (
	MediaDataModeID      = chat.MediaDataModeID
	MediaDataModeKeyID   = chat.MediaDataModeKeyID
	MediaDataModePayload = chat.MediaDataModePayload
)

Media data modes identify the supported message lookup strategies.

View Source
const (
	ActionInstanceCreate security.Action = enums.ActionInstanceCreate
	ActionInstanceList   security.Action = enums.ActionInstanceList
	ActionInstanceView   security.Action = enums.ActionInstanceView
	ActionInstanceUpdate security.Action = enums.ActionInstanceUpdate
	ActionInstanceDelete security.Action = enums.ActionInstanceDelete
)

Instance actions identify permissions for instance lifecycle operations.

View Source
const (
	ActionConnectionPair   security.Action = enums.ActionConnectionPair
	ActionConnectionView   security.Action = enums.ActionConnectionView
	ActionConnectionLogout security.Action = enums.ActionConnectionLogout
)

Connection actions identify permissions for pairing and session operations.

View Source
const (
	ActionWebhookSet  security.Action = enums.ActionWebhookSet
	ActionWebhookView security.Action = enums.ActionWebhookView
)

Webhook actions identify permissions for webhook configuration operations.

View Source
const (
	ActionMessageSend          security.Action = enums.ActionMessageSend
	ActionMessageList          security.Action = enums.ActionMessageList
	ActionMessageRead          security.Action = enums.ActionMessageRead
	ActionMessageDelete        security.Action = enums.ActionMessageDelete
	ActionMessageEdit          security.Action = enums.ActionMessageEdit
	ActionMessageMediaDownload security.Action = enums.ActionMessageMediaDownload
)

Message actions identify permissions for message operations.

View Source
const (
	ActionContactCheck       security.Action = enums.ActionContactCheck
	ActionChatArchive        security.Action = enums.ActionChatArchive
	ActionProfilePictureView security.Action = enums.ActionProfilePictureView
	ActionCallReject         security.Action = enums.ActionCallReject
)

Contact, chat, profile and call actions identify their respective permissions.

View Source
const (
	ActionGroupCreate            security.Action = enums.ActionGroupCreate
	ActionGroupPictureUpdate     security.Action = enums.ActionGroupPictureUpdate
	ActionGroupInviteView        security.Action = enums.ActionGroupInviteView
	ActionGroupInviteRevoke      security.Action = enums.ActionGroupInviteRevoke
	ActionGroupParticipantUpdate security.Action = enums.ActionGroupParticipantUpdate
	ActionGroupLeave             security.Action = enums.ActionGroupLeave
)

Group actions identify permissions for group operations.

View Source
const (
	// DefaultPrefix is where the module mounts its routes when Config.Prefix is empty.
	DefaultPrefix = appconfig.DefaultPrefix
	// DefaultWebhookRetention is the default lifetime of durable delivery snapshots.
	DefaultWebhookRetention = appconfig.DefaultWebhookRetention

	// DefaultWebhookConfigurationCacheTTL is the dispatch-side reuse window
	// applied when WebhookConfig.ConfigurationCacheTTL is left at zero.
	DefaultWebhookConfigurationCacheTTL = appconfig.DefaultWebhookConfigurationCacheTTL
	// DefaultProcessingRetention is the default lifetime of recoverable processing snapshots.
	DefaultProcessingRetention = appconfig.DefaultProcessingRetention
)
View Source
const (
	// DefaultInstancePageLimit is used when an instance query omits its limit.
	DefaultInstancePageLimit = repositories.DefaultInstancePageLimit
	// MaxInstancePageLimit is the largest accepted instance page.
	MaxInstancePageLimit = repositories.MaxInstancePageLimit
)
View Source
const ActionRuntime security.Action = enums.ActionRuntime

ActionRuntime identifies the internal permission used by background work.

View Source
const ActionRuntimeDiscover security.Action = enums.ActionRuntimeDiscover

ActionRuntimeDiscover identifies the internal permission the boot restore uses to list which tenants have instances to reconnect.

View Source
const MessageQueueName = message.MessageQueueName

MessageQueueName is the native queue the host worker and queue health module must monitor for durable mention-all sends.

View Source
const WebhookQueueName = webhooksvc.WebhookQueueName

WebhookQueueName is the native queue the host worker and queue health module must monitor for webhook deliveries.

Variables

View Source
var (
	// ErrForbidden means authorization, tenant scope or Grant validation refused an operation.
	ErrForbidden = security.ErrForbidden
	// ErrInstanceNotFound means the requested instance does not exist in the Grant tenant.
	ErrInstanceNotFound = models.ErrInstanceNotFound
	// ErrInstanceNameAlreadyExists means the Grant tenant already owns the requested name.
	ErrInstanceNameAlreadyExists = models.ErrInstanceNameAlreadyExists
	// ErrInstanceHasDependencies means a non-forced delete found owned records.
	ErrInstanceHasDependencies = models.ErrInstanceHasDependencies
	// ErrWhatsAppDeviceAlreadyLinked means the device is already assigned to another instance.
	ErrWhatsAppDeviceAlreadyLinked = models.ErrWhatsAppDeviceAlreadyLinked
	// ErrWebhookAlreadyExists means an instance already owns a webhook configuration.
	ErrWebhookAlreadyExists = models.ErrWebhookAlreadyExists
	// ErrWebhookNotFound means the requested webhook configuration does not exist.
	ErrWebhookNotFound = models.ErrWebhookNotFound
	// ErrMessageNotFound means the requested persisted message does not exist.
	ErrMessageNotFound = models.ErrMessageNotFound
	// ErrInvalidWebhookEvent means a webhook event name is unsupported.
	ErrInvalidWebhookEvent = models.ErrInvalidWebhookEvent
	// ErrInvalidWebhookURL means a webhook destination is not acceptable.
	ErrInvalidWebhookURL = models.ErrInvalidWebhookURL
	// ErrInvalidJSON means a JSON field is syntactically invalid or has the wrong shape.
	ErrInvalidJSON = models.ErrInvalidJSON
	// ErrInvalidEnum means a persisted enum value is unsupported.
	ErrInvalidEnum = models.ErrInvalidEnum
	// ErrInvalidInput means a public operation received invalid input.
	ErrInvalidInput = models.ErrInvalidInput
	// ErrInvalidCursor means an instance page cursor is malformed or outside the scoped result set.
	ErrInvalidCursor = models.ErrInvalidCursor

	// ErrConnectionInProgress means another pairing or connection attempt owns the instance.
	ErrConnectionInProgress = internalwhatsapp.ErrConnectionInProgress
	// ErrInstanceConnected means the instance is already connected.
	ErrInstanceConnected = internalwhatsapp.ErrInstanceConnected
	// ErrQRCodeTimeout means QR pairing did not produce a code before its deadline.
	ErrQRCodeTimeout = internalwhatsapp.ErrQRCodeTimeout
	// ErrQRChannelClosed means the QR event channel closed before pairing completed.
	ErrQRChannelClosed = internalwhatsapp.ErrQRChannelClosed
	// ErrPairingFailed means WhatsApp rejected or aborted pairing.
	ErrPairingFailed = internalwhatsapp.ErrPairingFailed
	// ErrClientOutdated means the WhatsApp client must be upgraded before connecting.
	ErrClientOutdated = internalwhatsapp.ErrClientOutdated
	// ErrWhatsAppUnavailable means the upstream WhatsApp service is unavailable.
	ErrWhatsAppUnavailable = internalwhatsapp.ErrWhatsAppUnavailable
	// ErrSchemaUnavailable means the module's tables or the WhatsMeow store have
	// not been migrated yet. The module boots anyway and answers every operation
	// with this error, which also matches ErrWhatsAppUnavailable, until
	// `aru migrate` has run.
	ErrSchemaUnavailable = internalwhatsapp.ErrSchemaUnavailable
	// ErrInvalidPhoneNumber means a phone number cannot be normalized for pairing.
	ErrInvalidPhoneNumber = internalwhatsapp.ErrInvalidPhoneNumber
	// ErrSessionMissing means the instance has no usable WhatsApp session.
	ErrSessionMissing = internalwhatsapp.ErrSessionMissing
	// ErrClientNotConnected means the operation requires an active WhatsApp client.
	ErrClientNotConnected = internalwhatsapp.ErrClientNotConnected
	// ErrInstanceInactive means the instance is not enabled for the requested operation.
	ErrInstanceInactive = internalwhatsapp.ErrInstanceInactive
	// ErrDeviceMismatch means the connected WhatsApp device does not match the instance.
	ErrDeviceMismatch = internalwhatsapp.ErrDeviceMismatch
	// ErrPasskeyInstanceNotFound means Passkey pairing cannot find the requested instance.
	ErrPasskeyInstanceNotFound = internalwhatsapp.ErrPasskeyInstanceNotFound
	// ErrPairingSessionNotFound means no Passkey pairing session exists for the request.
	ErrPairingSessionNotFound = internalwhatsapp.ErrPairingSessionNotFound
	// ErrPairingSessionNotActive means the Passkey pairing session cannot accept the operation.
	ErrPairingSessionNotActive = internalwhatsapp.ErrPairingSessionNotActive
	// ErrInvalidPairingState means the requested transition is invalid for the pairing state.
	ErrInvalidPairingState = internalwhatsapp.ErrInvalidPairingState
	// ErrPasskeyRequestMismatch means an assertion does not belong to the active request.
	ErrPasskeyRequestMismatch = internalwhatsapp.ErrPasskeyRequestMismatch
	// ErrPasskeyChallengeAlreadyUsed means the challenge has already accepted an assertion.
	ErrPasskeyChallengeAlreadyUsed = internalwhatsapp.ErrPasskeyChallengeAlreadyUsed
	// ErrPasskeyChallengeExpired means the Passkey challenge is no longer valid.
	ErrPasskeyChallengeExpired = internalwhatsapp.ErrPasskeyChallengeExpired
	// ErrInvalidPasskeyAssertion means the submitted assertion is invalid.
	ErrInvalidPasskeyAssertion = internalwhatsapp.ErrInvalidPasskeyAssertion
	// ErrPasskeyNotAvailable means the instance cannot use Passkey pairing.
	ErrPasskeyNotAvailable = internalwhatsapp.ErrPasskeyNotAvailable
	// ErrPasskeyServiceUnavailable means the Passkey integration is unavailable.
	ErrPasskeyServiceUnavailable = internalwhatsapp.ErrPasskeyServiceUnavailable

	// ErrInvalidMessageRequest means an outbound message request is invalid.
	ErrInvalidMessageRequest = message.ErrInvalidRequest
	// ErrRecipientInvalid means the outbound recipient is invalid.
	ErrRecipientInvalid = message.ErrRecipientInvalid
	// ErrPresenceInvalid means the requested outbound presence is invalid.
	ErrPresenceInvalid = message.ErrPresenceInvalid
	// ErrDelayInvalid means the requested outbound delay is invalid.
	ErrDelayInvalid = message.ErrDelayInvalid
	// ErrQuotedMessageInvalid means quoted-message input is invalid.
	ErrQuotedMessageInvalid = message.ErrQuotedMessageInvalid
	// ErrQuotedMessageLookup means the quoted message could not be loaded.
	ErrQuotedMessageLookup = message.ErrQuotedMessageLookup
	// ErrMessagePersistenceFailed means WhatsApp accepted a message that could not be persisted.
	ErrMessagePersistenceFailed = message.ErrPersistenceFailed
	// ErrMediaDownloadFailed means outbound media could not be downloaded.
	ErrMediaDownloadFailed = message.ErrDownloadFailed
	// ErrMediaUploadFailed means outbound media could not be uploaded to WhatsApp.
	ErrMediaUploadFailed = message.ErrUploadFailed
	// ErrMessageSendFailed means WhatsApp did not accept the outbound message.
	ErrMessageSendFailed = message.ErrSendFailed
	// ErrPayloadTooLarge means a message or attachment exceeds the configured limit.
	ErrPayloadTooLarge = message.ErrPayloadTooLarge
	// ErrUnsupportedMediaType means an outbound message uses an unsupported media type.
	ErrUnsupportedMediaType = message.ErrUnsupportedMediaType
	// ErrAudioProcessing means audio conversion or inspection failed.
	ErrAudioProcessing = message.ErrAudioProcessing
	// ErrInvalidAudioDuration means an audio duration is missing or outside the accepted range.
	ErrInvalidAudioDuration = message.ErrInvalidAudioDuration
	// ErrMentionAllRequiresGroup means mention-all was requested for a non-group recipient.
	ErrMentionAllRequiresGroup = message.ErrMentionAllRequiresGroup
	// ErrMentionAllUnsupported means the message type cannot carry mention-all metadata.
	ErrMentionAllUnsupported = message.ErrMentionAllUnsupported
	// ErrGroupInfoFetchFailed means mention processing could not load group information.
	ErrGroupInfoFetchFailed = message.ErrGroupInfoFetchFailed
	// ErrGroupHasNoParticipants means mention-all found no group participants.
	ErrGroupHasNoParticipants = message.ErrGroupHasNoParticipants
	// ErrGroupMentionProcessing means mention-all processing failed.
	ErrGroupMentionProcessing = message.ErrGroupMentionProcessing

	// ErrChatInstanceDisconnected means a chat operation requires a connected instance.
	ErrChatInstanceDisconnected = chat.ErrInstanceDisconnected
	// ErrMessageNotOutgoing means the instance did not send the targeted message.
	ErrMessageNotOutgoing = chat.ErrMessageNotOutgoing
	// ErrMessageNotEditable means WhatsApp does not permit editing the targeted message.
	ErrMessageNotEditable = chat.ErrMessageNotEditable
	// ErrChatInvalidRecipient means a chat operation received an invalid recipient.
	ErrChatInvalidRecipient = chat.ErrInvalidRecipient
	// ErrInvalidRequestMode means a message search mode is unsupported.
	ErrInvalidRequestMode = chat.ErrInvalidRequestMode
	// ErrDatabaseOperation means a chat operation failed while accessing persistence.
	ErrDatabaseOperation = chat.ErrDatabaseOperation
	// ErrChatRemoteOperation means a remote WhatsApp chat operation failed.
	ErrChatRemoteOperation = chat.ErrRemoteOperation
	// ErrInvalidMediaRequest means a media download request is invalid.
	ErrInvalidMediaRequest = chat.ErrInvalidMediaRequest
	// ErrMediaMessageNotFound means the requested media message does not exist.
	ErrMediaMessageNotFound = chat.ErrMediaMessageNotFound
	// ErrChatUnsupportedMediaType means stored media has an unsupported type.
	ErrChatUnsupportedMediaType = chat.ErrUnsupportedMediaType
	// ErrInvalidMediaContent means stored media content is invalid.
	ErrInvalidMediaContent = chat.ErrInvalidMediaContent
	// ErrMessageIsNotMedia means the requested message has no downloadable media.
	ErrMessageIsNotMedia = chat.ErrMessageIsNotMedia
	// ErrChatMediaDownloadFailed means WhatsApp could not return stored media.
	ErrChatMediaDownloadFailed = chat.ErrMediaDownloadFailed
	// ErrMediaTooLarge means downloaded chat media exceeds the configured limit.
	ErrMediaTooLarge = chat.ErrMediaTooLarge

	// ErrGroupInstanceDisconnected means a group operation requires a connected instance.
	ErrGroupInstanceDisconnected = group.ErrInstanceDisconnected
	// ErrInvalidGroupJID means the supplied group address is invalid.
	ErrInvalidGroupJID = group.ErrInvalidGroupJID
	// ErrInvalidParticipant means a group participant address is invalid.
	ErrInvalidParticipant = group.ErrInvalidParticipant
	// ErrInvalidGroupRequest means a group operation request is invalid.
	ErrInvalidGroupRequest = group.ErrInvalidRequest
	// ErrGroupRemoteOperation means a remote WhatsApp group operation failed.
	ErrGroupRemoteOperation = group.ErrRemoteOperation
	// ErrGroupDownloadFailed means a group image could not be downloaded.
	ErrGroupDownloadFailed = group.ErrDownloadFailed
	// ErrGroupImageTooLarge means a group image exceeds the configured limit.
	ErrGroupImageTooLarge = group.ErrImageTooLarge

	// ErrInvalidAddress means a WhatsApp address cannot be parsed or normalized.
	ErrInvalidAddress = address.ErrInvalidAddress
	// ErrRecipientNotOnWhatsApp means the resolved recipient is not registered on WhatsApp.
	ErrRecipientNotOnWhatsApp = address.ErrRecipientNotOnWhatsApp
	// ErrAmbiguousRecipient means more than one canonical recipient matches the input.
	ErrAmbiguousRecipient = address.ErrAmbiguousRecipient
	// ErrAddressMappingNotFound means no persisted alias mapping exists.
	ErrAddressMappingNotFound = address.ErrAddressMappingNotFound
)
View Source
var Actions = append([]security.Action(nil), enums.Actions...)

Actions is a snapshot of the complete public permission vocabulary.

Functions

This section is empty.

Types

type ArchiveChatRequest

type ArchiveChatRequest = chat.ArchiveChatRequest

ArchiveChatRequest is the input for changing a chat archive state.

type AudioMessageRequest

type AudioMessageRequest = httprequest.AudioMessageRequest

AudioMessageRequest contains outbound audio content.

type Config

type Config struct {
	// Tenant is the realm a visitor with no session is read as, and the tenant
	// the boot discovery runs under. It does not limit which tenants the module
	// serves: one registration hosts every tenant of the application, the
	// policy compares each instance's tenant with the subject's, and every
	// instance is reconnected, persisted and dispatched under a runtime Grant
	// of its own tenant.
	Tenant string
	// Prefix is the absolute path under which the module mounts its routes.
	Prefix string
	// WhatsApp controls pairing, reconnect and device behavior.
	WhatsApp WhatsAppConfig
	// Persistence selects the inbound data retained by the module.
	Persistence PersistenceConfig
	// Webhooks controls outbound webhook delivery.
	Webhooks WebhookConfig
	// Processing controls durable mention-all execution and retention.
	Processing ProcessingConfig
	// Media controls downloads, transcoding and temporary files.
	Media MediaConfig
	// Policy maps explicitly opened actions to application roles.
	Policy PolicyConfig
}

Config is the complete typed configuration for the WhatsApp module. The package never reads environment variables; the host application owns that translation and passes the result here.

func (Config) Validate

func (c Config) Validate() error

Validate reports unusable configuration before any worker or network client is started.

type ConnectionStateResult

type ConnectionStateResult = internalwhatsapp.ConnectionStateResult

ConnectionStateResult describes the current connection state of an instance.

type ContactMessage

type ContactMessage = httprequest.ContactMessage

ContactMessage contains one outbound contact card.

type CreateInstanceInput

type CreateInstanceInput struct {
	// Name is the stable public name. A generated name is used when it is absent.
	Name *string `json:"name,omitempty"`
	// Description is optional human-readable instance metadata.
	Description *string `json:"description,omitempty"`
	// ExternalAttributes holds caller-defined JSON object metadata.
	ExternalAttributes json.RawMessage `json:"externalAttributes,omitempty"`
}

CreateInstanceInput is the explicit instance creation contract.

type DeleteResult

type DeleteResult = internalwhatsapp.DeleteResult

DeleteResult describes the outcome of deleting an instance.

type DeviceMessage

type DeviceMessage = dbtypes.DeviceMessage

DeviceMessage identifies the client class that produced a message.

type Documentation

type Documentation = documentation.Registry

Documentation is the narrow Arandu Swagger registry contract required to publish the WhatsApp HTTP contract.

type EditMessageRequest

type EditMessageRequest = chat.EditMessageRequest

EditMessageRequest is the input for editing a sent message.

type FetchProfilePictureRequest

type FetchProfilePictureRequest = chat.FetchProfilePictureRequest

FetchProfilePictureRequest is the input for fetching a profile picture.

type FindMessagesRequest

type FindMessagesRequest = chat.FindMessagesRequest

FindMessagesRequest is the input for listing stored messages.

type FindMessagesWhere

type FindMessagesWhere = chat.FindMessagesWhere

FindMessagesWhere contains optional stored-message filters.

type FlexibleBool

type FlexibleBool = chat.FlexibleBool

FlexibleBool accepts boolean JSON values in native or string form.

type GroupCreateRequest

type GroupCreateRequest = group.CreateRequest

GroupCreateRequest is the input for creating a group.

type GroupInfoResponse

type GroupInfoResponse = group.InfoResponse

GroupInfoResponse describes a WhatsApp group.

type GroupInviteCodeResponse

type GroupInviteCodeResponse = group.InviteCodeResponse

GroupInviteCodeResponse describes a group's active invite code.

type GroupParticipantResponse

type GroupParticipantResponse = group.ParticipantResponse

GroupParticipantResponse describes one group participant.

type GroupUpdateParticipantRequest

type GroupUpdateParticipantRequest = group.UpdateParticipantRequest

GroupUpdateParticipantRequest is the input for changing group participants.

type GroupUpdatePictureRequest

type GroupUpdatePictureRequest = group.UpdatePictureRequest

GroupUpdatePictureRequest is the input for replacing a group picture.

type InboundListener added in v0.5.0

type InboundListener func(ctx context.Context, grant security.Grant, message InboundMessage)

InboundListener is told about every message an instance persisted, after it was persisted, with the runtime Grant of that instance's tenant: the tenant the listener writes under is the Grant's, and a listener never sees a message of another tenant under it.

It runs on the instance's event goroutine. A listener that does slow work hands it to the application's queue; a panic is recovered and logged.

type InboundMessage added in v0.5.0

type InboundMessage struct {
	// InstanceName is the instance it arrived on, unique inside its tenant.
	InstanceName string
	// KeyID is WhatsApp's identifier of the message.
	KeyID string
	// RemoteJID is the chat: the contact, or the group.
	RemoteJID string
	// Participant is who sent it inside a group, and empty in a direct chat.
	Participant string
	// PushName is the name the sender shows, when WhatsApp sent one.
	PushName string
	// FromMe is a message the paired phone itself sent.
	FromMe bool
	// IsGroup is a message in a group chat.
	IsGroup bool
	// MessageType is the kind of content, such as "conversation" for text.
	MessageType string
	// Content is the normalized content, as the messages table stores it.
	Content json.RawMessage
	// At is when WhatsApp says the message was sent.
	At time.Time
}

InboundMessage is one message an instance received or sent from the paired phone, as it was persisted.

type Instance

type Instance struct {
	// ID is the instance identifier.
	ID int64
	// TenantID is the tenant that owns the instance.
	TenantID string
	// Name is the stable public instance name.
	Name string
	// Description is optional human-readable metadata.
	Description *string
	// Status is the configured instance status.
	Status string
	// ConnectionStatus is the latest persisted connection state.
	ConnectionStatus string
	// OwnerJID is the legacy owner address when one is stored.
	OwnerJID *string
	// ProfilePictureURL is the latest known profile-picture URL.
	ProfilePictureURL *string
	// WhatsAppDeviceJID is the paired device address.
	WhatsAppDeviceJID *string
	// WhatsAppOwnerJID is the paired account address without device information.
	WhatsAppOwnerJID *string
	// WhatsAppPhone is the paired account phone number.
	WhatsAppPhone *string
	// LastConnectedAt is when the instance most recently connected.
	LastConnectedAt *time.Time
	// LastDisconnectedAt is when the instance most recently disconnected.
	LastDisconnectedAt *time.Time
	// ConnectionAttempts is the number of consecutive connection attempts.
	ConnectionAttempts int32
	// CreatedAt is when the instance was created.
	CreatedAt time.Time
	// UpdatedAt is when the instance was last updated.
	UpdatedAt time.Time
	// ExternalAttributes holds caller-defined JSON object metadata.
	ExternalAttributes json.RawMessage
}

Instance is the public WhatsApp instance entity protected by InstancePolicy.

type InstanceCollection

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

InstanceCollection is a tenant-scoped instance page.

func NewInstanceCollection

func NewInstanceCollection(page InstancePage) InstanceCollection

NewInstanceCollection wraps an instance page for an Arandu JSON response.

func (InstanceCollection) ToArray

func (c InstanceCollection) ToArray() map[string]any

ToArray returns the page items and forward-pagination metadata.

func (InstanceCollection) With

func (c InstanceCollection) With() map[string]any

With returns no top-level metadata.

type InstanceDependenciesError

type InstanceDependenciesError = internalrepo.InstanceDependenciesError

InstanceDependenciesError reports the owned record counts that blocked deletion.

type InstanceListQuery

type InstanceListQuery struct {
	// Name limits results to instance names containing this value.
	Name *string
	// Limit is the page size. Zero uses DefaultInstancePageLimit.
	Limit int
	// Cursor is the opaque NextCursor returned by the preceding page.
	Cursor string
}

InstanceListQuery selects one forward-only page of tenant instances.

type InstancePage

type InstancePage struct {
	// Items are the instances in this page.
	Items []Instance
	// NextCursor is empty when this is the final page.
	NextCursor string
	// PerPage is the normalized page size.
	PerPage int
}

InstancePage contains tenant instances and the cursor for the next page.

type InstancePolicy

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

InstancePolicy protects every operation on WhatsApp instances and their children. No role or action is enabled unless Config.Policy explicitly lists it.

func NewInstancePolicy

func NewInstancePolicy(cfg PolicyConfig) InstancePolicy

NewInstancePolicy builds a default-deny policy from typed role mappings and the actions decided by the subject's own actions.

func (InstancePolicy) Can

func (p InstancePolicy) Can(_ context.Context, subject security.Subject, action security.Action, instance Instance) error

Can decides whether a subject may perform an action on an instance.

func (InstancePolicy) Writes added in v0.8.0

func (InstancePolicy) Writes(action security.Action) bool

Writes reports whether a Grant issued for the action may write. A Grant issued to list or view an instance, or to view its webhook configuration, is refused by every write with auth.ErrReadGrant; every other action writes, because its flow can change the instance or store what it looked up.

type InstanceRepository

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

InstanceRepository is the public, Grant-first door to instance persistence. The native application repository receives the same explicit Grant and derives the tenant before reaching the database.

func NewInstanceRepository

func NewInstanceRepository(db *data.DB) *InstanceRepository

NewInstanceRepository returns an instance repository over the application database.

func (*InstanceRepository) Create

func (r *InstanceRepository) Create(ctx context.Context, grant security.Grant, entity Instance) (Instance, error)

Create stores a new instance in the Grant tenant.

func (*InstanceRepository) Delete

func (r *InstanceRepository) Delete(ctx context.Context, grant security.Grant, id int64) error

Delete removes one instance and its owned rows.

func (*InstanceRepository) Find

func (r *InstanceRepository) Find(ctx context.Context, grant security.Grant, id int64) (Instance, error)

Find returns one instance in the Grant tenant.

func (*InstanceRepository) FindByName

func (r *InstanceRepository) FindByName(ctx context.Context, grant security.Grant, name string) (Instance, error)

FindByName returns one instance by its stable public name.

func (*InstanceRepository) List

func (r *InstanceRepository) List(ctx context.Context, grant security.Grant, query data.Query) ([]Instance, error)

List returns one bounded tenant-scoped page for the legacy framework repository contract.

func (*InstanceRepository) ListPage

ListPage returns a bounded tenant-scoped page and its next cursor.

func (*InstanceRepository) Update

func (r *InstanceRepository) Update(ctx context.Context, grant security.Grant, entity Instance) (Instance, error)

Update changes the mutable instance metadata.

type InstanceResource

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

InstanceResource declares the fields that may leave the module. Tenant and the WhatsMeow device-store key are intentionally absent.

func NewInstanceResource

func NewInstanceResource(instance Instance) InstanceResource

NewInstanceResource wraps one instance for an Arandu JSON response.

func (InstanceResource) ToArray

func (r InstanceResource) ToArray() map[string]any

ToArray returns the public representation of an instance.

func (InstanceResource) With

func (r InstanceResource) With() map[string]any

With returns no top-level metadata.

type LinkMessage

type LinkMessage = httprequest.LinkMessage

LinkMessage contains link-message content and optional preview metadata.

type LocationMessage

type LocationMessage = httprequest.LocationMessage

LocationMessage contains outbound geographic coordinates and metadata.

type LogoutResult

type LogoutResult = internalwhatsapp.LogoutResult

LogoutResult describes the outcome of an instance logout.

type MediaConfig

type MediaConfig struct {
	// FFmpegPath is the ffmpeg executable path or command name.
	FFmpegPath string
	// FFprobePath is the ffprobe executable path or command name.
	FFprobePath string
	// TempDir is the parent for secure transient media directories.
	TempDir string
	// MaxInputBytes is the maximum accepted media input size.
	MaxInputBytes int64
	// MaxDurationSeconds is the maximum accepted audio duration.
	MaxDurationSeconds uint32
	// ProcessingTimeout bounds one media transformation.
	ProcessingTimeout time.Duration
}

MediaConfig declares external executable paths and bounded temporary-media settings. Empty executable paths use the conventional command names.

type MediaDataMode

type MediaDataMode = chat.MediaDataMode

MediaDataMode identifies how a media download request selects its message.

type MediaDataRequest

type MediaDataRequest = chat.MediaDataRequest

MediaDataRequest is the input for downloading message media.

type MediaDownloadResult

type MediaDownloadResult = chat.MediaDownloadResult

MediaDownloadResult describes downloaded message media.

type MediaMessage

type MediaMessage = httprequest.MediaMessage

MediaMessage contains outbound media content.

type MediaMetadata

type MediaMetadata = chat.MediaMetadata

MediaMetadata describes downloaded media content.

type Message

type Message = dbtypes.Message

Message is a persisted WhatsApp message.

type MessageIdentifier

type MessageIdentifier = chat.MessageIdentifier

MessageIdentifier identifies a stored message by numeric or WhatsApp key ID.

type MessageKey

type MessageKey = chat.MessageKeyDTO

MessageKey identifies a WhatsApp message.

type MessageListResult

type MessageListResult = dbtypes.MessageListResult

MessageListResult is a page of stored messages.

type MessageOptions

type MessageOptions = message.MessageOptions

MessageOptions configures optional outbound message behavior.

type MessagePage

type MessagePage = dbtypes.MessagePage

MessagePage contains stored messages and page metadata.

type MessageReference

type MessageReference = chat.MessageReferenceDTO

MessageReference identifies the last message used by a chat operation.

type MessageUpdateSummary

type MessageUpdateSummary = dbtypes.MessageUpdateSummary

MessageUpdateSummary describes one message status transition.

type MessageWithUpdates

type MessageWithUpdates = dbtypes.MessageWithUpdates

MessageWithUpdates contains a stored message and its status history.

type Module

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

Module wires the WhatsApp domain into the Arandu lifecycle. The database and session store are borrowed from the host application and are never closed by this module.

func New

func New(cfg Config, db *data.DB, sessions *security.SessionStore) (*Module, error)

New validates configuration and assembles all collaborators without doing database I/O, starting goroutines, connecting to WhatsApp or running schema changes. That keeps commands such as `aru migrate` and `aru route:list` side-effect free.

func NewWithDocumentation

func NewWithDocumentation(
	cfg Config,
	db *data.DB,
	sessions *security.SessionStore,
	docs Documentation,
) (*Module, error)

NewWithDocumentation builds the WhatsApp module and registers its reusable OpenAPI components on the supplied Arandu Swagger instance. The host application still owns and explicitly registers the Swagger module.

func (*Module) Available added in v0.8.1

func (m *Module) Available() error

Available answers nil when the module can serve, and otherwise why it cannot: an error matching ErrSchemaUnavailable until `aru migrate` has run. It is cheap and safe to call from a request, a health page or a login screen.

func (*Module) Boot

func (m *Module) Boot(context.Context) error

Boot prepares the process-global WhatsMeow device descriptor. It performs no database or network work.

func (*Module) Close

func (m *Module) Close(ctx context.Context) error

Close stops producers before consumers while leaving the shared database, SessionStore and WhatsMeow container ownership with the host application.

func (*Module) Health

func (m *Module) Health(ctx context.Context) error

Health checks only module-owned runtime state and the borrowed database. It does not call WhatsApp or probe every connected device.

func (*Module) Migrations

func (m *Module) Migrations() []foundation.Migration

Migrations declares the module-owned domain schema and delegates the WhatsMeow store schema to its upstream container. They are never applied by New, Boot or Start.

func (*Module) Name

func (*Module) Name() string

Name is the stable module identifier used by Arandu route tooling.

func (*Module) OnInbound added in v0.5.0

func (m *Module) OnInbound(fn InboundListener)

OnInbound registers a listener for inbound messages. It is wiring: call it after New and before Start.

func (*Module) RegisterJobHandlers

func (m *Module) RegisterJobHandlers(worker *queue.Worker) error

RegisterJobHandlers registers every durable module job with the host application's native queue worker.

func (*Module) Routes

func (m *Module) Routes(r *fhttp.Router)

Routes registers the module's canonical named HTTP surface.

func (*Module) Service

func (m *Module) Service() *Service

Service exposes the authorized domain API for explicit composition by the host application.

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

Start verifies that migrations were applied and, when they were, restores the paired connections asynchronously; the terminal error of that restoration is reported by Health. Durable jobs are owned by the host queue worker.

A schema that is not migrated yet does not stop the process. A new image can boot before `aru migrate` has run, and a module that refused to start took the whole application down with it (a four-minute outage in production). Start logs the error, the module reports itself through Available and answers every operation with ErrSchemaUnavailable, and a background goroutine looks again every few seconds, restoring the connections once the schema appears. Health stays nil: readiness is the application's, and an optional capability that has not been migrated must not make the rest of it unready.

A closed database or disabled SQLite foreign keys are configuration errors, not a pending migration, and still fail Start.

type PasskeyAssertionResult

type PasskeyAssertionResult = internalwhatsapp.PasskeyAssertionResult

PasskeyAssertionResult describes the outcome of a Passkey assertion.

type PasskeyChallengeResult

type PasskeyChallengeResult = internalwhatsapp.PasskeyChallengeResult

PasskeyChallengeResult describes a Passkey pairing challenge.

type PasskeyPairingState

type PasskeyPairingState = internalwhatsapp.PasskeyPairingState

PasskeyPairingState identifies a stage in Passkey pairing.

type PersistenceConfig

type PersistenceConfig struct {
	// Messages retains inbound and outbound message snapshots.
	Messages bool
	// MessageUpdates retains receipt and status transitions.
	MessageUpdates bool
	// Contacts retains contact snapshots received from WhatsApp.
	Contacts bool
}

PersistenceConfig selects which asynchronous WhatsApp events are retained.

type PhonePairingInput

type PhonePairingInput struct {
	// PhoneNumber is the international phone number to pair.
	PhoneNumber string `json:"phoneNumber"`
}

PhonePairingInput is the JSON-safe input for phone-code pairing.

type PhonePairingResult

type PhonePairingResult = internalwhatsapp.PhonePairingResult

PhonePairingResult describes the outcome of phone-code pairing.

type PolicyConfig

type PolicyConfig struct {
	// Roles lists the roles allowed for each action. Missing actions are denied.
	Roles map[security.Action][]string
	// Actions lists the actions a subject may take when it carries that very
	// action, for an application whose permission groups fill the subject's
	// actions (arandu-permission) rather than its roles. Listing an action here
	// opens it to exactly the subjects whose groups grant it; an action in
	// neither list stays closed.
	Actions []security.Action
}

PolicyConfig maps each explicitly enabled action to the roles allowed to perform it. An empty map is the safe default and denies every action.

type ProcessingConfig

type ProcessingConfig struct {
	// Workers is retained for source compatibility and is ignored. Configure
	// concurrency with `aru queue:work --workers=N`.
	//
	// Deprecated: use the host queue worker concurrency instead.
	Workers int
	// QueueSize is retained for source compatibility and is ignored because the
	// native database queue is durable.
	//
	// Deprecated: the native database queue has no in-memory queue size.
	QueueSize int
	// ProcessingTimeout bounds the complete mention-all operation.
	ProcessingTimeout time.Duration
	// GroupInfoTimeout bounds the participant lookup used by mention-all.
	GroupInfoTimeout time.Duration
	// SendTimeout bounds the final WhatsApp send operation.
	SendTimeout time.Duration
	// Retention bounds how long a failed or abandoned mention-all snapshot and
	// its recoverable dead letter remain available. Zero uses
	// DefaultProcessingRetention.
	Retention time.Duration
}

ProcessingConfig controls durable mention-all execution.

type QRCodeConnectionResult

type QRCodeConnectionResult = internalwhatsapp.QRCodeConnectionResult

QRCodeConnectionResult describes the outcome of QR-code pairing.

type ReactionKey

type ReactionKey = httprequest.ReactionKey

ReactionKey identifies the message targeted by a reaction.

type ReactionMessage

type ReactionMessage = httprequest.ReactionMessage

ReactionMessage contains an outbound reaction and its target key.

type ReadMessagesRequest

type ReadMessagesRequest = chat.ReadMessagesRequest

ReadMessagesRequest is the input for marking messages as read.

type RejectCallRequest

type RejectCallRequest = chat.RejectCallRequest

RejectCallRequest is the input for rejecting a call.

type SendContactRequest

type SendContactRequest = message.SendContactRequest

SendContactRequest is the input for sending a contact card.

type SendLinkRequest

type SendLinkRequest = message.SendLinkRequest

SendLinkRequest is the input for sending a link message.

type SendLocationRequest

type SendLocationRequest = message.SendLocationRequest

SendLocationRequest is the input for sending a location.

type SendMediaRequest

type SendMediaRequest = message.SendMediaRequest

SendMediaRequest is the input for sending media.

type SendReactionRequest

type SendReactionRequest = message.SendReactionRequest

SendReactionRequest is the input for sending a message reaction.

type SendResult

type SendResult = message.SendResult

SendResult describes a persisted outbound message.

type SendTextRequest

type SendTextRequest = message.SendTextRequest

SendTextRequest is the input for sending a text message.

type SendWhatsAppAudioRequest

type SendWhatsAppAudioRequest = message.SendWhatsAppAudioRequest

SendWhatsAppAudioRequest is the input for sending WhatsApp audio.

type Service

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

Service is the nominal public facade over the native application service.

func (*Service) ArchiveChat

func (s *Service) ArchiveChat(ctx context.Context, actor security.Subject, name string, input ArchiveChatRequest) error

ArchiveChat changes the archive state of a chat.

func (*Service) CheckContacts

func (s *Service) CheckContacts(ctx context.Context, actor security.Subject, name string, input WhatsAppNumbersRequest) ([]WhatsAppNumberResponse, error)

CheckContacts reports which supplied contacts are registered on WhatsApp.

func (*Service) ConnectPhone

func (s *Service) ConnectPhone(ctx context.Context, actor security.Subject, name string, input PhonePairingInput) (PhonePairingResult, error)

ConnectPhone starts phone-code pairing for an instance.

func (*Service) ConnectQRCode

func (s *Service) ConnectQRCode(ctx context.Context, actor security.Subject, name string) (QRCodeConnectionResult, error)

ConnectQRCode starts QR-code pairing for an instance.

func (*Service) ConnectionState

func (s *Service) ConnectionState(ctx context.Context, actor security.Subject, name string) (ConnectionStateResult, error)

ConnectionState returns the current connection state of an instance.

func (*Service) CreateGroup

func (s *Service) CreateGroup(ctx context.Context, actor security.Subject, name string, input GroupCreateRequest) (GroupInfoResponse, error)

CreateGroup creates a WhatsApp group.

func (*Service) CreateInstance

func (s *Service) CreateInstance(ctx context.Context, actor security.Subject, input CreateInstanceInput) (Instance, error)

CreateInstance validates, authorizes and creates one instance.

func (*Service) DeleteInstance

func (s *Service) DeleteInstance(ctx context.Context, actor security.Subject, name string, force bool) (DeleteResult, error)

DeleteInstance deletes an instance and optionally forces dependency removal.

func (*Service) DeleteMessage

func (s *Service) DeleteMessage(ctx context.Context, actor security.Subject, name string, id int64) error

DeleteMessage deletes a message for every participant.

func (*Service) EditMessage

func (s *Service) EditMessage(ctx context.Context, actor security.Subject, name string, input EditMessageRequest) (Message, error)

EditMessage replaces the content of a sent message.

func (*Service) FindInstance

func (s *Service) FindInstance(ctx context.Context, actor security.Subject, name string) (Instance, error)

FindInstance returns one instance after both collection and record checks.

func (*Service) FindMessages

func (s *Service) FindMessages(ctx context.Context, actor security.Subject, name string, input FindMessagesRequest) (MessageListResult, error)

FindMessages returns messages matching the supplied query.

func (*Service) FindWebhook

func (s *Service) FindWebhook(ctx context.Context, actor security.Subject, name string) (Webhook, error)

FindWebhook returns the webhook configuration for an instance.

func (*Service) GroupInviteCode

func (s *Service) GroupInviteCode(ctx context.Context, actor security.Subject, name, groupJID string) (GroupInviteCodeResponse, error)

GroupInviteCode returns the active invite code for a group.

func (*Service) LeaveGroup

func (s *Service) LeaveGroup(ctx context.Context, actor security.Subject, name, groupJID string) error

LeaveGroup removes the connected account from a group.

func (*Service) ListInstances

func (s *Service) ListInstances(ctx context.Context, actor security.Subject, query InstanceListQuery) (InstancePage, error)

ListInstances returns one page of instances from the actor tenant.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, actor security.Subject, name string) (LogoutResult, error)

Logout disconnects an instance and removes its active WhatsApp session.

func (*Service) MediaData

func (s *Service) MediaData(ctx context.Context, actor security.Subject, name string, input MediaDataRequest) (MediaDownloadResult, error)

MediaData downloads media attached to a message.

func (*Service) PasskeyAssertion

PasskeyAssertion submits an assertion for the active Passkey challenge.

func (*Service) PasskeyChallenge

func (s *Service) PasskeyChallenge(ctx context.Context, actor security.Subject, name string) (PasskeyChallengeResult, error)

PasskeyChallenge requests the current Passkey pairing challenge.

func (*Service) ProfilePicture

func (s *Service) ProfilePicture(ctx context.Context, actor security.Subject, name string, input FetchProfilePictureRequest) (*string, error)

ProfilePicture returns the profile-picture URL for a contact or group.

func (*Service) ReadMessages

func (s *Service) ReadMessages(ctx context.Context, actor security.Subject, name string, input ReadMessagesRequest) error

ReadMessages marks the selected messages as read.

func (*Service) RejectCall

func (s *Service) RejectCall(ctx context.Context, actor security.Subject, name string, input RejectCallRequest) error

RejectCall rejects an incoming WhatsApp call.

func (*Service) RevokeGroupInvite

func (s *Service) RevokeGroupInvite(ctx context.Context, actor security.Subject, name, groupJID string) error

RevokeGroupInvite revokes the active invite code for a group.

func (*Service) SendAudio

func (s *Service) SendAudio(ctx context.Context, actor security.Subject, name string, input SendWhatsAppAudioRequest) (SendResult, error)

SendAudio sends an audio message described by a structured request.

func (*Service) SendAudioFile

func (s *Service) SendAudioFile(ctx context.Context, actor security.Subject, name, number string, file multipart.File, header *multipart.FileHeader, options *MessageOptions) (SendResult, error)

SendAudioFile sends an audio message from a multipart upload.

func (*Service) SendContact

func (s *Service) SendContact(ctx context.Context, actor security.Subject, name string, input SendContactRequest) (SendResult, error)

SendContact sends a contact card through an instance.

func (s *Service) SendLink(ctx context.Context, actor security.Subject, name string, input SendLinkRequest) (SendResult, error)

SendLink sends a link message through an instance.

func (*Service) SendLocation

func (s *Service) SendLocation(ctx context.Context, actor security.Subject, name string, input SendLocationRequest) (SendResult, error)

SendLocation sends a location message through an instance.

func (*Service) SendMedia

func (s *Service) SendMedia(ctx context.Context, actor security.Subject, name string, input SendMediaRequest) (SendResult, error)

SendMedia sends media described by a structured request.

func (*Service) SendMediaFile

func (s *Service) SendMediaFile(ctx context.Context, actor security.Subject, name, number string, file multipart.File, header *multipart.FileHeader, mediaType string, caption *string, options *MessageOptions) (SendResult, error)

SendMediaFile sends media from a multipart upload.

func (*Service) SendReaction

func (s *Service) SendReaction(ctx context.Context, actor security.Subject, name string, input SendReactionRequest) (SendResult, error)

SendReaction sends a reaction to an existing message.

func (*Service) SendText

func (s *Service) SendText(ctx context.Context, actor security.Subject, name string, input SendTextRequest) (SendResult, error)

SendText sends a text message through an instance.

func (*Service) SetWebhook

func (s *Service) SetWebhook(ctx context.Context, actor security.Subject, name string, input WebhookSetInput) (Webhook, error)

SetWebhook creates or updates the webhook configuration for an instance.

func (*Service) UpdateGroupParticipants

func (s *Service) UpdateGroupParticipants(ctx context.Context, actor security.Subject, name, groupJID string, input GroupUpdateParticipantRequest) error

UpdateGroupParticipants applies a participant membership or role change.

func (*Service) UpdateGroupPicture

func (s *Service) UpdateGroupPicture(ctx context.Context, actor security.Subject, name string, input GroupUpdatePictureRequest) (GroupInfoResponse, error)

UpdateGroupPicture replaces a group profile picture.

type SubmitPasskeyAssertionRequest

type SubmitPasskeyAssertionRequest = internalwhatsapp.SubmitPasskeyAssertionRequest

SubmitPasskeyAssertionRequest is the input for a Passkey assertion.

type TextMessage

type TextMessage = httprequest.TextMessage

TextMessage contains text-message content.

type ValidationError

type ValidationError = chat.ValidationError

ValidationError carries semantic request validation messages from chat operations.

type Webhook

type Webhook = dbtypes.Webhook

Webhook is the persisted webhook configuration of an instance.

type WebhookConfig

type WebhookConfig struct {
	// GlobalURL receives every enabled event in addition to instance webhooks.
	GlobalURL string
	// GlobalEnabled enables delivery to GlobalURL.
	GlobalEnabled bool
	// SigningSecret signs every outbound delivery with HMAC-SHA256. It is
	// required before any global or instance webhook can be enabled and must
	// contain at least 32 bytes after surrounding whitespace is ignored.
	SigningSecret string
	// Retention is the maximum lifetime of delivery snapshots. Zero uses
	// DefaultWebhookRetention.
	Retention time.Duration
	// ConfigurationCacheTTL is how long a dispatch reuses a webhook
	// configuration it already read, instead of reading it again.
	//
	// It bounds how long this process may keep dispatching against a
	// configuration another process changed; a change made through this process
	// takes effect at once. Zero uses DefaultWebhookConfigurationCacheTTL, and a
	// negative value is rejected.
	ConfigurationCacheTTL time.Duration
	// Workers is retained for source compatibility and is ignored. Configure
	// worker concurrency with `aru queue:work --workers=N`.
	//
	// Deprecated: use the host queue worker concurrency instead.
	Workers int
	// QueueSize is retained for source compatibility and is ignored because the
	// native database queue is durable.
	//
	// Deprecated: the native database queue has no in-memory queue size.
	QueueSize int
}

WebhookConfig controls the optional global destination. Durable delivery is processed by the host application's native queue worker.

type WebhookSetInput

type WebhookSetInput = webhooksvc.SetInput

WebhookSetInput is the input for creating or updating a webhook.

type WhatsAppConfig

type WhatsAppConfig struct {
	// QRCodeLimit is the maximum number of QR codes emitted by one pairing flow.
	QRCodeLimit int
	// QRCodeExpiration is how long one QR code remains usable.
	QRCodeExpiration time.Duration
	// QRCodeLightColor is the generated QR code background in #RRGGBB form.
	QRCodeLightColor string
	// QRCodeDarkColor is the generated QR code foreground in #RRGGBB form.
	QRCodeDarkColor string
	// SessionPhoneClient identifies the emulated WhatsApp client class.
	SessionPhoneClient string
	// SessionPhoneName is the device name WhatsApp displays for the session.
	SessionPhoneName string
	// PairingTimeout bounds one QR, phone-code or Passkey pairing flow.
	PairingTimeout time.Duration
	// AutoReconnect restores eligible sessions when the module starts.
	AutoReconnect bool
	// StartupReconnectConcurrency bounds parallel session restoration.
	StartupReconnectConcurrency int
	// ConnectTimeout bounds one WhatsApp connection attempt.
	ConnectTimeout time.Duration
	// ReconnectInitialDelay is the first delay between reconnect attempts.
	ReconnectInitialDelay time.Duration
	// ReconnectMaxDelay caps reconnect backoff.
	ReconnectMaxDelay time.Duration
	// ProfilePictureTimeout bounds profile-picture lookups.
	ProfilePictureTimeout time.Duration
	// AddressCacheTTL controls persisted phone-to-JID resolution freshness.
	AddressCacheTTL time.Duration
}

WhatsAppConfig controls device identity, pairing, reconnect and address resolution.

type WhatsAppNumberResponse

type WhatsAppNumberResponse = chat.WhatsAppNumberResponse

WhatsAppNumberResponse describes one WhatsApp contact check.

type WhatsAppNumbersRequest

type WhatsAppNumbersRequest = chat.WhatsAppNumbersRequest

WhatsAppNumbersRequest is the input for checking WhatsApp contacts.

Directories

Path Synopsis
app
Enums
Package enums declares the WhatsApp module's shared value vocabularies.
Package enums declares the WhatsApp module's shared value vocabularies.
Http/Documentation
Package apidocs declares the native Arandu Swagger contract contributed by the WhatsApp module.
Package apidocs declares the native Arandu Swagger contract contributed by the WhatsApp module.
Http/Requests
Package requests holds the typed inputs accepted by the WhatsApp module.
Package requests holds the typed inputs accepted by the WhatsApp module.
Http/Resources
Package resources declares the fields that may leave through HTTP responses.
Package resources declares the fields that may leave through HTTP responses.
Jobs
Package jobs declares the durable jobs owned by the WhatsApp module.
Package jobs declares the durable jobs owned by the WhatsApp module.
Models
Package models holds the domain values shared across module responsibilities.
Package models holds the domain values shared across module responsibilities.
Policies
Package policies contains the module's authorization decisions.
Package policies contains the module's authorization decisions.
Repositories
Package repositories contains the Grant-first persistence adapters.
Package repositories contains the Grant-first persistence adapters.
Services
Package services holds the authorized business rules of the WhatsApp module.
Package services holds the authorized business rules of the WhatsApp module.
cmd
webhook-docs command
Package config defines the WhatsApp module's typed configuration.
Package config defines the WhatsApp module's typed configuration.
database
migrations
Package migrations declares the ordered schema changes owned by the WhatsApp module.
Package migrations declares the ordered schema changes owned by the WhatsApp module.
internal
authz
Package authz owns the authorization vocabulary shared by the public package and its internal persistence adapters.
Package authz owns the authorization vocabulary shared by the public package and its internal persistence adapters.
config
Package config contains the runtime settings consumed by the WhatsApp implementation.
Package config contains the runtime settings consumed by the WhatsApp implementation.
domain
Package domain holds contracts shared by the module's application and infrastructure responsibilities.
Package domain holds contracts shared by the module's application and infrastructure responsibilities.
Package routes declares the canonical named HTTP surface of the module.
Package routes declares the canonical named HTTP surface of the module.

Jump to

Keyboard shortcuts

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