-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
168 lines (145 loc) 路 5.3 KB
/
Copy pathmain.go
File metadata and controls
168 lines (145 loc) 路 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Command matrix-absence-bot logs into your own Matrix account and sends an
// automatic "I'm away" reply to direct messages, at most once per sender per
// day. There is no schedule or toggle: you are "absent" for exactly as long
// as this process is running. Start it before you leave, Ctrl-C it when
// you're back.
package main
import (
"context"
"flag"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"github.com/rs/zerolog"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto/cryptohelper"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
func main() {
configPath := flag.String("config", "config.yaml", "path to config file")
flag.Parse()
log := zerolog.New(zerolog.NewConsoleWriter()).With().Timestamp().Logger()
cfg, err := LoadConfig(*configPath)
if err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
if err := ensureParentDirs(cfg.CryptoDBPath, cfg.StatePath); err != nil {
log.Fatal().Err(err).Msg("Failed to create data directory")
}
client, err := mautrix.NewClient(cfg.Homeserver, id.UserID(cfg.UserID), cfg.AccessToken)
if err != nil {
log.Fatal().Err(err).Msg("Failed to create client")
}
client.DeviceID = id.DeviceID(cfg.DeviceID)
client.Log = log
// Sent as set_presence on every /sync request. Without this, the mere
// act of the bot polling /sync marks the account "online" on every
// request - regardless of the auto-reply - which is why presence would
// otherwise always show as available while the bot runs.
client.SyncPresence = event.Presence(cfg.Presence)
syncer := mautrix.NewDefaultSyncer()
client.Syncer = syncer
cryptoHelper, err := cryptohelper.NewCryptoHelper(client, []byte(cfg.PickleKey), cfg.CryptoDBPath)
if err != nil {
log.Fatal().Err(err).Msg("Failed to set up crypto helper")
}
ctx := context.Background()
if err := cryptoHelper.Init(ctx); err != nil {
log.Fatal().Err(err).Msg("Failed to initialize crypto helper")
}
client.Crypto = cryptoHelper
defer cryptoHelper.Close()
rateLimiter, err := NewRateLimiter(cfg.StatePath)
if err != nil {
log.Fatal().Err(err).Msg("Failed to load rate limiter state")
}
dmTracker := NewDMTracker()
handler := NewHandler(client, dmTracker, rateLimiter, cfg.ReplyMessage, log)
// Track completion of the first sync round-trip so we know once it's
// safe to start reacting to messages (and can run the recovery-key
// verification, which needs an initial sync to have happened).
firstSyncChan := make(chan struct{})
var closeOnce sync.Once
syncer.OnSync(func(_ context.Context, _ *mautrix.RespSync, _ string) bool {
closeOnce.Do(func() { close(firstSyncChan) })
return true
})
syncer.OnEventType(event.EventMessage, handler.HandleMessage)
syncer.OnEventType(event.AccountDataDirectChats, dmTracker.HandleAccountData)
syncStopped := make(chan error, 1)
go func() {
syncStopped <- client.Sync()
}()
log.Info().Msg("Waiting for initial sync...")
select {
case <-firstSyncChan:
log.Info().Msg("Initial sync complete")
case err := <-syncStopped:
log.Fatal().Err(err).Msg("Sync stopped before completing initial sync")
}
if err := dmTracker.Load(ctx, client); err != nil {
log.Error().Err(err).Msg("Failed to load initial DM room list; will rely on live updates")
}
if cfg.RecoveryKey != "" {
if err := verifyWithRecoveryKey(ctx, cryptoHelper, cfg.RecoveryKey); err != nil {
log.Error().Err(err).Msg("Failed to verify device with recovery key; decryption of some rooms may not work until this device is verified from another client")
} else {
log.Info().Msg("Device verified via recovery key")
}
} else {
log.Warn().Msg("No recovery_key configured; decryption may not work until this device is verified from another client")
}
handler.MarkFirstSyncDone()
log.Info().Msg("Absence bot is running - auto-replying to direct messages")
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
select {
case sig := <-sigCh:
log.Info().Str("signal", sig.String()).Msg("Shutting down")
client.StopSync()
case err := <-syncStopped:
if err != nil {
log.Fatal().Err(err).Msg("Sync stopped unexpectedly")
}
}
}
// ensureParentDirs creates the parent directory of each given path if it
// doesn't already exist, so a fresh deployment (e.g. an empty mounted
// volume, or a data directory that was never created) doesn't fail just
// because crypto.db/state.json have nowhere to go yet.
func ensureParentDirs(paths ...string) error {
for _, p := range paths {
dir := filepath.Dir(p)
if dir == "." || dir == "" {
continue
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
}
return nil
}
// verifyWithRecoveryKey uses the account's SSSS recovery key to cross-sign
// this device, so other devices trust it and share room (megolm) keys with
// it - without this, encrypted DMs may never decrypt.
func verifyWithRecoveryKey(ctx context.Context, ch *cryptohelper.CryptoHelper, recoveryKey string) error {
machine := ch.Machine()
keyID, keyData, err := machine.SSSS.GetDefaultKeyData(ctx)
if err != nil {
return err
}
key, err := keyData.VerifyRecoveryKey(keyID, recoveryKey)
if err != nil {
return err
}
if err := machine.FetchCrossSigningKeysFromSSSS(ctx, key); err != nil {
return err
}
if err := machine.SignOwnDevice(ctx, machine.OwnIdentity()); err != nil {
return err
}
return machine.SignOwnMasterKey(ctx)
}