Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(app): add passkey pairing support (#754)

Aldino Kemala66f8835091d
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index c2f3c590..5ce9e4b1 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -83,6 +83,95 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /app/passkey:
+ get:
+ operationId: appPasskeyStatus
+ tags:
+ - app
+ summary: Get pending passkey pairing state
+ description: >
+ Passkey pairing is initiated from the phone during QR login. When the phone requests it,
+ the server sends a WebAuthn challenge which is stored here (also broadcast over the
+ websocket as PASSKEY_REQUEST) until a response is submitted.
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PasskeyStatusResponse'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+ /app/passkey/response:
+ post:
+ operationId: appPasskeyResponse
+ tags:
+ - app
+ summary: Submit the WebAuthn assertion for passkey pairing
+ description: >
+ Send the WebAuthn assertion produced for the pending challenge (see GET /app/passkey).
+ The assertion must be produced by an authenticator holding the WhatsApp account's passkey,
+ against WhatsApp's relying-party ID; the payload format matches PublicKeyCredential.toJSON().
+ If the assertion is submitted within the 5-minute handoff window, pairing is confirmed
+ automatically; otherwise a confirmation code is issued (PASSKEY_CONFIRMATION websocket event)
+ and must be confirmed via POST /app/passkey/confirm.
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/WebAuthnAssertion'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+ /app/passkey/confirm:
+ post:
+ operationId: appPasskeyConfirm
+ tags:
+ - app
+ summary: Confirm the passkey pairing code
+ description: >
+ Confirms that the pairing code from the PASSKEY_CONFIRMATION event was shown to the user
+ and matches the code displayed on the phone. Only needed when skip_handoff_ux is false.
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
/app/logout:
get:
operationId: appLogout
@@ -3926,6 +4015,90 @@ components:
qr_link:
type: string
example: 'http://localhost:3000/statics/images/qrcode/scan-qr-b0b7bb43-9a22-455a-814f-5a225c743310.png'
+ PasskeyStatusResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Passkey pairing status
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ example: device-1
+ status:
+ type: string
+ enum: [none, awaiting_response, awaiting_confirmation]
+ example: awaiting_response
+ challenge:
+ type: object
+ nullable: true
+ description: WebAuthn assertion request options (PublicKeyCredentialRequestOptions JSON, base64url-encoded binary fields)
+ properties:
+ challenge:
+ type: string
+ example: dGVzdC1jaGFsbGVuZ2U
+ timeout:
+ type: integer
+ example: 60000
+ rpId:
+ type: string
+ example: whatsapp.com
+ allowCredentials:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ type:
+ type: string
+ example: public-key
+ transports:
+ type: array
+ items:
+ type: string
+ userVerification:
+ type: string
+ example: required
+ code:
+ type: string
+ description: Pairing confirmation code (set while awaiting confirmation)
+ example: ABCD-EFGH
+ skip_handoff_ux:
+ type: boolean
+ example: false
+ WebAuthnAssertion:
+ type: object
+ description: WebAuthn assertion in PublicKeyCredential.toJSON() format (binary fields base64url-encoded without padding)
+ required: [id, rawId, type, response]
+ properties:
+ id:
+ type: string
+ example: XcnXe2W9me1XZTGii6JI9A
+ rawId:
+ type: string
+ example: XcnXe2W9me1XZTGii6JI9A
+ type:
+ type: string
+ example: public-key
+ response:
+ type: object
+ required: [clientDataJSON, authenticatorData, signature]
+ properties:
+ clientDataJSON:
+ type: string
+ authenticatorData:
+ type: string
+ signature:
+ type: string
+ userHandle:
+ type: string
+ nullable: true
GenericResponse:
type: object
properties:
diff --git a/readme.md b/readme.md
index 055cccec..65aa21e7 100644
--- a/readme.md
+++ b/readme.md
@@ -545,6 +545,9 @@ You can fork or edit this source code !
| ✅ | Get Device Status | GET | /devices/:device_id/status |
| ✅ | Login with Scan QR | GET | /app/login |
| ✅ | Login With Pair Code | GET | /app/login-with-code |
+| ✅ | Passkey Pairing Status | GET | /app/passkey |
+| ✅ | Passkey Pairing Response | POST | /app/passkey/response |
+| ✅ | Passkey Pairing Confirm | POST | /app/passkey/confirm |
| ✅ | Logout | GET | /app/logout |
| ✅ | Reconnect | GET | /app/reconnect |
| ✅ | Devices | GET | /app/devices |
diff --git a/src/domains/app/app.go b/src/domains/app/app.go
index 4854a9ee..15b5b47b 100644
--- a/src/domains/app/app.go
+++ b/src/domains/app/app.go
@@ -3,11 +3,16 @@ package app
import (
"context"
"time"
+
+ "go.mau.fi/whatsmeow/types"
)
type IAppUsecase interface {
Login(ctx context.Context, deviceID string) (response LoginResponse, err error)
LoginWithCode(ctx context.Context, deviceID string, phoneNumber string) (loginCode string, err error)
+ PasskeyChallenge(ctx context.Context, deviceID string) (response PasskeyChallengeResponse, err error)
+ PasskeyResponse(ctx context.Context, deviceID string, assertion *types.WebAuthnResponse) (err error)
+ PasskeyConfirm(ctx context.Context, deviceID string) (err error)
Logout(ctx context.Context, deviceID string) (err error)
Reconnect(ctx context.Context, deviceID string) (err error)
Status(ctx context.Context, deviceID string) (isConnected bool, isLoggedIn bool, err error)
@@ -26,3 +31,10 @@ type LoginResponse struct {
Duration time.Duration `json:"duration"`
Code string `json:"code"`
}
+
+type PasskeyChallengeResponse struct {
+ Status string `json:"status"` // "none" | "awaiting_response" | "awaiting_confirmation"
+ Challenge *types.WebAuthnPublicKey `json:"challenge,omitempty"`
+ Code string `json:"code,omitempty"`
+ SkipHandoffUX bool `json:"skip_handoff_ux,omitempty"`
+}
diff --git a/src/infrastructure/whatsapp/device_instance.go b/src/infrastructure/whatsapp/device_instance.go
index 20e4e2e2..a7581870 100644
--- a/src/infrastructure/whatsapp/device_instance.go
+++ b/src/infrastructure/whatsapp/device_instance.go
@@ -7,6 +7,7 @@ import (
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
"go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
)
// DeviceInstance bundles a WhatsApp client with device metadata and scoped storage.
@@ -21,6 +22,11 @@ type DeviceInstance struct {
jid string
createdAt time.Time
onLoggedOut func(deviceID string) // Callback for remote logout cleanup
+
+ // Pending passkey pairing state, populated by PairPasskey* events during login.
+ passkeyChallenge *types.WebAuthnPublicKey
+ passkeyCode string
+ passkeySkipHandoffUX bool
}
func NewDeviceInstance(deviceID string, client *whatsmeow.Client, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceInstance {
@@ -168,6 +174,40 @@ func (d *DeviceInstance) refreshIdentityLocked() {
}
}
+// SetPasskeyChallenge stores a pending WebAuthn challenge and clears any previous confirmation code.
+func (d *DeviceInstance) SetPasskeyChallenge(pk *types.WebAuthnPublicKey) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.passkeyChallenge = pk
+ d.passkeyCode = ""
+ d.passkeySkipHandoffUX = false
+}
+
+// SetPasskeyConfirmation stores the pairing confirmation code and clears the pending challenge.
+func (d *DeviceInstance) SetPasskeyConfirmation(code string, skipHandoffUX bool) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.passkeyChallenge = nil
+ d.passkeyCode = code
+ d.passkeySkipHandoffUX = skipHandoffUX
+}
+
+// PasskeyState returns the pending challenge, confirmation code and skip-handoff flag.
+func (d *DeviceInstance) PasskeyState() (*types.WebAuthnPublicKey, string, bool) {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.passkeyChallenge, d.passkeyCode, d.passkeySkipHandoffUX
+}
+
+// ClearPasskeyState resets all pending passkey pairing state.
+func (d *DeviceInstance) ClearPasskeyState() {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.passkeyChallenge = nil
+ d.passkeyCode = ""
+ d.passkeySkipHandoffUX = false
+}
+
func (d *DeviceInstance) SetOnLoggedOut(callback func(deviceID string)) {
d.mu.Lock()
defer d.mu.Unlock()
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 29a39ac7..1fac6431 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -37,7 +37,14 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {
case *events.AppStateSyncComplete:
handleAppStateSyncComplete(ctx, client, evt)
case *events.PairSuccess:
+ instance.ClearPasskeyState()
handlePairSuccess(ctx, evt)
+ case *events.PairPasskeyRequest:
+ handlePairPasskeyRequest(instance, evt)
+ case *events.PairPasskeyConfirmation:
+ handlePairPasskeyConfirmation(instance, evt)
+ case *events.PairPasskeyError:
+ handlePairPasskeyError(instance, evt)
case *events.LoggedOut:
handleLoggedOut(instance)
case *events.Connected, *events.PushNameSetting:
@@ -153,8 +160,51 @@ func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {
syncKeysDevice(ctx, primaryDB, secondaryDB, evt.ID)
}
+func handlePairPasskeyRequest(instance *DeviceInstance, evt *events.PairPasskeyRequest) {
+ instance.SetPasskeyChallenge(evt.PublicKey)
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "PASSKEY_REQUEST",
+ Message: "Passkey pairing requested; submit the WebAuthn assertion via POST /app/passkey/response",
+ Result: map[string]any{
+ "device_id": instance.ID(),
+ "challenge": evt.PublicKey,
+ },
+ }
+}
+
+func handlePairPasskeyConfirmation(instance *DeviceInstance, evt *events.PairPasskeyConfirmation) {
+ instance.SetPasskeyConfirmation(evt.Code, evt.SkipHandoffUX)
+ message := fmt.Sprintf("Passkey pairing code %s: verify it matches the code on your phone, then confirm via POST /app/passkey/confirm", evt.Code)
+ if evt.SkipHandoffUX {
+ message = "Passkey pairing verified, finishing automatically"
+ }
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "PASSKEY_CONFIRMATION",
+ Message: message,
+ Result: map[string]any{
+ "device_id": instance.ID(),
+ "code": evt.Code,
+ "skip_handoff_ux": evt.SkipHandoffUX,
+ },
+ }
+}
+
+func handlePairPasskeyError(instance *DeviceInstance, evt *events.PairPasskeyError) {
+ logrus.Warnf("[PASSKEY][%s] pairing error (continuation=%t): %v", instance.ID(), evt.Continuation, evt.Error)
+ instance.ClearPasskeyState()
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "PASSKEY_ERROR",
+ Message: evt.Error.Error(),
+ Result: map[string]any{
+ "device_id": instance.ID(),
+ "continuation": evt.Continuation,
+ },
+ }
+}
+
func handleLoggedOut(instance *DeviceInstance) {
logrus.Warnf("[REMOTE_LOGOUT] Received LoggedOut event for device %s - user logged out from phone", instance.ID())
+ instance.ClearPasskeyState()
if client := instance.GetClient(); client != nil {
client.Disconnect()
diff --git a/src/infrastructure/whatsapp/event_handler_passkey_test.go b/src/infrastructure/whatsapp/event_handler_passkey_test.go
new file mode 100644
index 00000000..17eafa99
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_handler_passkey_test.go
@@ -0,0 +1,70 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func recvBroadcast(t *testing.T) websocket.BroadcastMessage {
+ t.Helper()
+ select {
+ case msg := <-websocket.Broadcast:
+ return msg
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for websocket broadcast")
+ return websocket.BroadcastMessage{}
+ }
+}
+
+func TestHandlerPasskeyEvents(t *testing.T) {
+ ctx := context.Background()
+ instance := NewDeviceInstance("test-passkey", nil, nil)
+
+ // PairPasskeyRequest stores the challenge and broadcasts PASSKEY_REQUEST.
+ publicKey := &types.WebAuthnPublicKey{RelyingPartID: "whatsapp.com"}
+ go handler(ctx, instance, &events.PairPasskeyRequest{PublicKey: publicKey})
+ if msg := recvBroadcast(t); msg.Code != "PASSKEY_REQUEST" {
+ t.Errorf("broadcast code = %s, want PASSKEY_REQUEST", msg.Code)
+ }
+ challenge, code, _ := instance.PasskeyState()
+ if challenge != publicKey || code != "" {
+ t.Errorf("PasskeyState() after request = (%v, %q), want stored challenge and empty code", challenge, code)
+ }
+
+ // PairPasskeyConfirmation stores the code and broadcasts PASSKEY_CONFIRMATION.
+ go handler(ctx, instance, &events.PairPasskeyConfirmation{Code: "ABCD-EFGH", SkipHandoffUX: true})
+ if msg := recvBroadcast(t); msg.Code != "PASSKEY_CONFIRMATION" {
+ t.Errorf("broadcast code = %s, want PASSKEY_CONFIRMATION", msg.Code)
+ }
+ challenge, code, skip := instance.PasskeyState()
+ if challenge != nil || code != "ABCD-EFGH" || !skip {
+ t.Errorf("PasskeyState() after confirmation = (%v, %q, %t), want (nil, ABCD-EFGH, true)", challenge, code, skip)
+ }
+
+ // PairPasskeyError clears the state and broadcasts PASSKEY_ERROR.
+ go handler(ctx, instance, &events.PairPasskeyError{Error: errors.New("boom")})
+ if msg := recvBroadcast(t); msg.Code != "PASSKEY_ERROR" {
+ t.Errorf("broadcast code = %s, want PASSKEY_ERROR", msg.Code)
+ }
+ challenge, code, skip = instance.PasskeyState()
+ if challenge != nil || code != "" || skip {
+ t.Errorf("PasskeyState() after error = (%v, %q, %t), want cleared", challenge, code, skip)
+ }
+
+ // PairSuccess clears any leftover passkey state alongside the LOGIN_SUCCESS broadcast.
+ instance.SetPasskeyChallenge(publicKey)
+ go handler(ctx, instance, &events.PairSuccess{})
+ if msg := recvBroadcast(t); msg.Code != "LOGIN_SUCCESS" {
+ t.Errorf("broadcast code = %s, want LOGIN_SUCCESS", msg.Code)
+ }
+ challenge, code, skip = instance.PasskeyState()
+ if challenge != nil || code != "" || skip {
+ t.Errorf("PasskeyState() after pair success = (%v, %q, %t), want cleared", challenge, code, skip)
+ }
+}
diff --git a/src/ui/rest/app.go b/src/ui/rest/app.go
index 25803299..52969c35 100644
--- a/src/ui/rest/app.go
+++ b/src/ui/rest/app.go
@@ -8,6 +8,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
+ "go.mau.fi/whatsmeow/types"
)
type App struct {
@@ -18,6 +19,9 @@ func InitRestApp(app fiber.Router, service domainApp.IAppUsecase) App {
rest := App{Service: service}
app.Get("/app/login", rest.Login)
app.Get("/app/login-with-code", rest.LoginWithCode)
+ app.Get("/app/passkey", rest.PasskeyChallenge)
+ app.Post("/app/passkey/response", rest.PasskeyResponse)
+ app.Post("/app/passkey/confirm", rest.PasskeyConfirm)
app.Get("/app/logout", rest.Logout)
app.Get("/app/reconnect", rest.Reconnect)
app.Get("/app/devices", rest.Devices)
@@ -67,6 +71,68 @@ func (handler *App) LoginWithCode(c *fiber.Ctx) error {
})
}
+func (handler *App) PasskeyChallenge(c *fiber.Ctx) error {
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ response, err := handler.Service.PasskeyChallenge(c.UserContext(), device.ID())
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Passkey pairing status",
+ Results: map[string]any{
+ "device_id": device.ID(),
+ "status": response.Status,
+ "challenge": response.Challenge,
+ "code": response.Code,
+ "skip_handoff_ux": response.SkipHandoffUX,
+ },
+ })
+}
+
+func (handler *App) PasskeyResponse(c *fiber.Ctx) error {
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ var assertion types.WebAuthnResponse
+ if err := c.BodyParser(&assertion); err != nil {
+ return fiber.NewError(fiber.StatusBadRequest, "invalid WebAuthn assertion payload: "+err.Error())
+ }
+
+ err = handler.Service.PasskeyResponse(c.UserContext(), device.ID(), &assertion)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Passkey response sent",
+ Results: map[string]any{"device_id": device.ID()},
+ })
+}
+
+func (handler *App) PasskeyConfirm(c *fiber.Ctx) error {
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ err = handler.Service.PasskeyConfirm(c.UserContext(), device.ID())
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Passkey pairing confirmed",
+ Results: map[string]any{"device_id": device.ID()},
+ })
+}
+
func (handler *App) Logout(c *fiber.Ctx) error {
device, err := getDeviceInstance(c)
if err != nil {
diff --git a/src/usecase/app.go b/src/usecase/app.go
index 7404ac50..4f50f03f 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -19,6 +19,7 @@ import (
"github.com/skip2/go-qrcode"
"go.mau.fi/libsignal/logger"
"go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
)
type serviceApp struct {
@@ -46,6 +47,7 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
// Disconnect first to ensure QR flow starts cleanly.
client.Disconnect()
+ instance.ClearPasskeyState()
// Use a detached context for the QR channel so the pairing session
// survives after the HTTP response is sent. The HTTP request context
@@ -94,6 +96,9 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
logrus.Warnf("[LOGIN][%s] QR context canceled while sending QR path", deviceID)
return
}
+ } else if evt.Event == whatsmeow.QRChannelEventPasskeyRequest || evt.Event == whatsmeow.QRChannelEventPasskeyResponse {
+ // Passkey events are broadcast by the global event handler and served via /app/passkey endpoints.
+ logrus.Infof("[LOGIN][%s] passkey pairing event: %s", deviceID, evt.Event)
} else {
logrus.Errorf("[LOGIN][%s] error when get qrCode %s %v", deviceID, evt.Event, evt.Error)
}
@@ -159,6 +164,100 @@ func (service *serviceApp) LoginWithCode(ctx context.Context, deviceID string, p
return loginCode, nil
}
+func (service *serviceApp) PasskeyChallenge(_ context.Context, deviceID string) (response domainApp.PasskeyChallengeResponse, err error) {
+ if service.deviceManager == nil {
+ return response, fmt.Errorf("device manager not initialized")
+ }
+
+ instance, ok := service.deviceManager.GetDevice(deviceID)
+ if !ok || instance == nil {
+ return response, fmt.Errorf("device %s not found", deviceID)
+ }
+
+ challenge, code, skipHandoffUX := instance.PasskeyState()
+ response.Status = "none"
+ if challenge != nil {
+ response.Status = "awaiting_response"
+ } else if code != "" {
+ response.Status = "awaiting_confirmation"
+ }
+ response.Challenge = challenge
+ response.Code = code
+ response.SkipHandoffUX = skipHandoffUX
+ return response, nil
+}
+
+func (service *serviceApp) PasskeyResponse(ctx context.Context, deviceID string, assertion *types.WebAuthnResponse) error {
+ if err := validations.ValidatePasskeyResponse(ctx, assertion); err != nil {
+ return err
+ }
+
+ if service.deviceManager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ instance, ok := service.deviceManager.GetDevice(deviceID)
+ if !ok || instance == nil {
+ return fmt.Errorf("device %s not found", deviceID)
+ }
+
+ client := instance.GetClient()
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ challenge, _, _ := instance.PasskeyState()
+ if challenge == nil {
+ return fmt.Errorf("no pending passkey pairing request for device %s", deviceID)
+ }
+
+ if !client.IsConnected() {
+ return fmt.Errorf("device %s is not connected, restart login and retry the passkey flow", deviceID)
+ }
+
+ if err := client.SendPasskeyResponse(ctx, assertion); err != nil {
+ logrus.Errorf("[PASSKEY][%s] failed to send passkey response: %v", deviceID, err)
+ return err
+ }
+
+ // The PairPasskeyConfirmation event repopulates the confirmation code shortly after.
+ instance.ClearPasskeyState()
+ return nil
+}
+
+func (service *serviceApp) PasskeyConfirm(ctx context.Context, deviceID string) error {
+ if service.deviceManager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ instance, ok := service.deviceManager.GetDevice(deviceID)
+ if !ok || instance == nil {
+ return fmt.Errorf("device %s not found", deviceID)
+ }
+
+ client := instance.GetClient()
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ _, code, _ := instance.PasskeyState()
+ if code == "" {
+ return fmt.Errorf("no pending passkey confirmation for device %s", deviceID)
+ }
+
+ if !client.IsConnected() {
+ return fmt.Errorf("device %s is not connected, restart login and retry the passkey flow", deviceID)
+ }
+
+ if err := client.SendPasskeyConfirmation(ctx); err != nil {
+ logrus.Errorf("[PASSKEY][%s] failed to send passkey confirmation: %v", deviceID, err)
+ return err
+ }
+
+ instance.ClearPasskeyState()
+ return nil
+}
+
func (service *serviceApp) Logout(ctx context.Context, deviceID string) error {
if err := validations.ValidateDeviceID(ctx, deviceID); err != nil {
return err
diff --git a/src/validations/app_validation.go b/src/validations/app_validation.go
index e9eb1f70..9752e571 100644
--- a/src/validations/app_validation.go
+++ b/src/validations/app_validation.go
@@ -5,6 +5,7 @@ import (
"fmt"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
validation "github.com/go-ozzo/ozzo-validation/v4"
+ "go.mau.fi/whatsmeow/types"
"regexp"
)
@@ -19,3 +20,31 @@ func ValidateLoginWithCode(ctx context.Context, phoneNumber string) error {
}
return nil
}
+
+func ValidatePasskeyResponse(ctx context.Context, response *types.WebAuthnResponse) error {
+ if response == nil {
+ return pkgError.ValidationError("assertion payload is required")
+ }
+
+ err := validation.ValidateStructWithContext(ctx, response,
+ validation.Field(&response.ID, validation.Required),
+ validation.Field(&response.Type, validation.Required, validation.In("public-key")),
+ )
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ if len(response.RawID) == 0 {
+ return pkgError.ValidationError("rawId: cannot be blank")
+ }
+ if len(response.Response.ClientDataJSON) == 0 {
+ return pkgError.ValidationError("response.clientDataJSON: cannot be blank")
+ }
+ if len(response.Response.AuthenticatorData) == 0 {
+ return pkgError.ValidationError("response.authenticatorData: cannot be blank")
+ }
+ if len(response.Response.Signature) == 0 {
+ return pkgError.ValidationError("response.signature: cannot be blank")
+ }
+ return nil
+}
diff --git a/src/validations/app_validation_test.go b/src/validations/app_validation_test.go
index 5757b324..8f3b4b71 100644
--- a/src/validations/app_validation_test.go
+++ b/src/validations/app_validation_test.go
@@ -2,7 +2,11 @@ package validations
import (
"context"
+ "encoding/json"
"testing"
+
+ "github.com/stretchr/testify/assert"
+ "go.mau.fi/whatsmeow/types"
)
func TestValidateLoginWithCode(t *testing.T) {
@@ -59,3 +63,85 @@ func TestValidateLoginWithCode(t *testing.T) {
})
}
}
+
+func TestValidatePasskeyResponse(t *testing.T) {
+ // Sample PublicKeyCredential.toJSON() output. The binary fields are unpadded
+ // base64url encodings of obviously fake placeholders (e.g. "fake-signature")
+ // so secret scanners don't flag them as high-entropy credentials.
+ validJSON := `{
+ "id": "ZmFrZS1jcmVkZW50aWFsLWlk",
+ "rawId": "ZmFrZS1jcmVkZW50aWFsLWlk",
+ "type": "public-key",
+ "response": {
+ "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0",
+ "authenticatorData": "ZmFrZS1hdXRoZW50aWNhdG9yLWRhdGE",
+ "signature": "ZmFrZS1zaWduYXR1cmU",
+ "userHandle": null
+ }
+ }`
+
+ parse := func(t *testing.T, raw string) *types.WebAuthnResponse {
+ var resp types.WebAuthnResponse
+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {
+ t.Fatalf("failed to unmarshal sample assertion: %v", err)
+ }
+ return &resp
+ }
+
+ tests := []struct {
+ name string
+ mutate func(r *types.WebAuthnResponse) *types.WebAuthnResponse
+ wantErr string // expected error substring; empty means no error
+ }{
+ {
+ name: "valid PublicKeyCredential.toJSON payload",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { return r },
+ },
+ {
+ name: "nil payload",
+ mutate: func(*types.WebAuthnResponse) *types.WebAuthnResponse { return nil },
+ wantErr: "assertion payload is required",
+ },
+ {
+ name: "missing id",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.ID = ""; return r },
+ wantErr: "id: cannot be blank",
+ },
+ {
+ name: "missing rawId",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.RawID = nil; return r },
+ wantErr: "rawId: cannot be blank",
+ },
+ {
+ name: "wrong type",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.Type = "password"; return r },
+ wantErr: "type: must be a valid value",
+ },
+ {
+ name: "missing signature",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.Response.Signature = nil; return r },
+ wantErr: "response.signature: cannot be blank",
+ },
+ {
+ name: "missing authenticatorData",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.Response.AuthenticatorData = nil; return r },
+ wantErr: "response.authenticatorData: cannot be blank",
+ },
+ {
+ name: "missing clientDataJSON",
+ mutate: func(r *types.WebAuthnResponse) *types.WebAuthnResponse { r.Response.ClientDataJSON = nil; return r },
+ wantErr: "response.clientDataJSON: cannot be blank",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidatePasskeyResponse(context.Background(), tt.mutate(parse(t, validJSON)))
+ if tt.wantErr == "" {
+ assert.NoError(t, err)
+ } else {
+ assert.ErrorContains(t, err, tt.wantErr)
+ }
+ })
+ }
+}
diff --git a/src/views/index.html b/src/views/index.html
index 4b77f393..54f91bb7 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -412,6 +412,21 @@
}
break;
}
+ case 'PASSKEY_REQUEST':
+ showSuccessInfo('Passkey linking requested. Complete the WebAuthn assertion via the REST API (GET /app/passkey).')
+ break;
+ case 'PASSKEY_CONFIRMATION':
+ if (message.result?.skip_handoff_ux) {
+ showSuccessInfo(message.message)
+ } else if (window.confirm('Does this passkey pairing code match the one on your phone? ' + (message.result?.code || ''))) {
+ window.http.post('app/passkey/confirm')
+ .then(() => showSuccessInfo('Passkey pairing confirmed'))
+ .catch(err => showErrorInfo(err?.response?.data?.message || 'Passkey confirmation failed'))
+ }
+ break;
+ case 'PASSKEY_ERROR':
+ showErrorInfo(message.message)
+ break;
case 'DEVICE_LOGGED_OUT': {
// Logout keeps the slot: refresh the list (device is now
// disconnected) but keep the current selection so the user