Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ jobs:
npm run check:api --if-present
npm run lint --if-present
npm run format:check --if-present
node --test tests/feishu-summary.test.mjs
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ multiple accounts, localised searches and an optional Control API.
- Desktop/mobile searches, Explore on Bing, Daily Check-In and Read to Earn.
- Optional Visual Search and background Edge browsing.
- Streak progress, API-based streak protection and verified point reporting.
- Scheduled runs, account selection, saved sessions and Discord/Telegram/ntfy notifications.
- Scheduled runs, account selection, saved sessions and Discord/Telegram/ntfy notifications, plus Feishu/Lark account summaries.
- Control API with live events, persistent history, punchcard progress and activity balance observations.

Activities depend on the account and region. This branch contains v5; earlier
Expand Down
5 changes: 5 additions & 0 deletions config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@
"enabled": false,
"url": ""
},
"feishu": {
"enabled": false,
"url": "",
"signingSecret": ""
},
"telegram": {
"enabled": false,
"botToken": "",
Expand Down
5 changes: 4 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -444,17 +444,20 @@ A match in any level, keyword or regex rule counts. Debug console output still r

Set each service under `webhook`.

Environment names use `CONFIG_DISCORD_*`, `CONFIG_TELEGRAM_*` or `CONFIG_NTFY_*`; see the examples below.
Environment names use `CONFIG_DISCORD_*`, `CONFIG_TELEGRAM_*`, `CONFIG_NTFY_*` or `CONFIG_FEISHU_*`; see the examples below.

| Service | Enable and configure | Optional fields |
| ---------- | ------------------------------- | --------------------------------------------- |
| `discord` | `enabled`, `url` | - |
| `feishu` | `enabled`, `url` | `signingSecret` |
| `telegram` | `enabled`, `botToken`, `chatId` | - |
| `ntfy` | `enabled`, `url` | `topic`, `token`, `title`, `tags`, `priority` |

- All services are disabled by default.
- ntfy defaults: title `Microsoft-Rewards-Script`, tags `["bot", "notify"]`, priority `3` on a `1–5` scale.
- Technical debug output is kept out of notification webhooks.
- Feishu/Lark sends one summary per account after its tasks finish, including completed, incomplete, unavailable and not-applicable activities. Account email is not included. Delivery failures do not stop reward tasks. This channel is independent of the log filter.
- Configure a Feishu or Lark custom bot URL and, if the bot uses signature verification, its signing secret. Keep both private. Supported environment overrides: `CONFIG_FEISHU_ENABLED`, `CONFIG_FEISHU_URL`, and `CONFIG_FEISHU_SIGNING_SECRET`.

Example Discord settings:

Expand Down
7 changes: 7 additions & 0 deletions src/config/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,16 @@ export interface ConfigWebhook {
discord?: WebhookDiscordConfig
ntfy?: WebhookNtfyConfig
telegram?: WebhookTelegramConfig
feishu?: WebhookFeishuConfig
webhookLogFilter: LogFilter
}

export interface WebhookFeishuConfig {
enabled: boolean
url: string
signingSecret?: string
}

export interface LogFilter {
enabled: boolean
mode: 'whitelist' | 'blacklist'
Expand Down
3 changes: 3 additions & 0 deletions src/config/ConfigEnvOverrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ export const ENV_OVERRIDES: EnvOverrideEntry[] = [
{ env: 'CONFIG_LOG_FILTER_KEYWORDS', path: 'consoleLogFilter.keywords', type: 'array' },

// Discord webhook
{ env: 'CONFIG_FEISHU_ENABLED', path: 'webhook.feishu.enabled', type: 'bool' },
{ env: 'CONFIG_FEISHU_URL', path: 'webhook.feishu.url', type: 'string' },
{ env: 'CONFIG_FEISHU_SIGNING_SECRET', path: 'webhook.feishu.signingSecret', type: 'string' },
{ env: 'CONFIG_DISCORD_ENABLED', path: 'webhook.discord.enabled', type: 'bool' },
{ env: 'CONFIG_DISCORD_URL', path: 'webhook.discord.url', type: 'string' },

Expand Down
1 change: 1 addition & 0 deletions src/config/Defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const defaultConfig: Config = {
proxy: { queryEngine: true, ignoreCertificateErrors: false },
webhook: {
discord: { enabled: false, url: '' },
feishu: { enabled: false, url: '', signingSecret: '' },
telegram: { enabled: false, botToken: '', chatId: '' },
ntfy: {
enabled: false,
Expand Down
1 change: 1 addition & 0 deletions src/config/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ const AccountCountrySchema = z
)

const WebhookSchema = z.strictObject({
feishu: z.strictObject({ enabled: z.boolean(), url: z.string(), signingSecret: z.string().optional() }).optional(),
discord: z
.strictObject({
enabled: z.boolean(),
Expand Down
2 changes: 2 additions & 0 deletions src/control-api/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export function redactSecrets(config) {
const mask = '***REDACTED***'
const wh = clone.webhook
if (wh && typeof wh === 'object') {
if (wh.feishu?.url) wh.feishu.url = mask
if (wh.feishu?.signingSecret) wh.feishu.signingSecret = mask
if (wh.discord?.url) wh.discord.url = mask
if (wh.ntfy?.url) wh.ntfy.url = mask
if (wh.ntfy?.token) wh.ntfy.token = mask
Expand Down
107 changes: 107 additions & 0 deletions src/logging/Feishu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { createHmac } from 'node:crypto'
import PQueue from 'p-queue'
import type { AccountStats } from '../core/RunTypes'
import type { CompletionDetail } from '../rewards/shared/ActivityCompletion'
import type { WebhookFeishuConfig } from '../config/Config'
import { logSystemMessage } from './LogEvent'
import { flushQueue } from './Queue'

const queue = new PQueue({ concurrency: 1 })
const MAX_ITEMS = 12

function safeText(value: string): string {
return value
.replace(/https?:\/\/\S+/gi, '[link]')
.replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, '[email]')
.replace(/[\r\n<>[\]`*_\\]/g, ' ')
.slice(0, 160)
}

function formatItems(items: CompletionDetail[] | undefined, total: number): string {
const shown = (items ?? []).slice(0, MAX_ITEMS)
const lines = shown.map(item => {
const platform = item.platform === 'mobile' ? 'Mobile' : item.platform === 'desktop' ? 'Desktop' : 'General'
const title = item.title ? `: ${safeText(item.title)}` : ''
const points =
item.pointsKnown !== false && (item.pointsGained ?? 0) > 0 ? ` (+${item.pointsGained} points)` : ''
const message = item.category !== 'completed' && item.message ? ` — ${safeText(item.message)}` : ''
return `• ${platform} ${safeText(item.label)}${title}${points}${message}`
})
if (total > shown.length) lines.push(`• ${total - shown.length} more`)
return lines.length ? lines.join('\n') : 'None'
}

export function createFeishuCard(stats: AccountStats) {
const status = stats.status ?? (stats.success ? 'completed' : 'partial')
const template = status === 'completed' ? 'green' : status === 'partial' ? 'orange' : 'red'
const heading =
status === 'completed' ? 'Completed' : status === 'partial' ? 'Partially completed' : 'Run failed or stopped'
const points =
stats.pointsKnown === false
? 'Points: unknown'
: `Points: ${stats.initialPoints} → ${stats.finalPoints} (${stats.collectedPoints >= 0 ? '+' : ''}${stats.collectedPoints})`
const completion = stats.completion
const text = completion
? `${points}\n\n**Completed**\n${formatItems(completion.completed, completion.counts.completed)}\n\n**Incomplete or unconfirmed**\n${formatItems(completion.incomplete, completion.counts.incomplete)}\n\n**Unavailable or skipped**\n${formatItems(completion.unavailable, completion.counts.unavailable)}\n\n**Not applicable**\n${formatItems(completion.notApplicable, completion.counts.notApplicable)}`
: `${points}\n\nTask details unavailable.`
return {
config: { wide_screen_mode: true },
header: { template, title: { tag: 'plain_text', content: `Microsoft Rewards · ${heading}` } },
elements: [{ tag: 'div', text: { tag: 'lark_md', content: text } }]
}
}

export function createFeishuPayload(stats: AccountStats, secret: string, timestamp: string) {
const signature = secret
? { timestamp, sign: createHmac('sha256', `${timestamp}\n${secret}`).update('').digest('base64') }
: {}
return { ...signature, msg_type: 'interactive', card: createFeishuCard(stats) }
}

export function isFeishuWebhook(value: string): boolean {
try {
const url = new URL(value)
return (
url.protocol === 'https:' &&
['open.feishu.cn', 'open.larksuite.com'].includes(url.hostname) &&
!url.username &&
!url.password &&
!url.port &&
!url.search &&
!url.hash &&
/^\/open-apis\/bot\/v2\/hook\/[A-Za-z0-9-]+$/.test(url.pathname)
)
} catch {
return false
}
}

export function sendFeishuSummary(config: WebhookFeishuConfig | undefined, stats: AccountStats): void {
if (!config?.enabled) return
if (!isFeishuWebhook(config.url)) {
logSystemMessage('warn', 'NOTIFICATIONS', 'Feishu webhook URL is invalid.')
return
}
void queue.add(async () => {
try {
const response = await fetch(config.url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
redirect: 'error',
body: JSON.stringify(
createFeishuPayload(stats, config.signingSecret ?? '', String(Math.floor(Date.now() / 1000)))
),
signal: AbortSignal.timeout(4000)
})
const result: unknown = await response.json()
if (!response.ok || !result || typeof result !== 'object' || !('code' in result) || result.code !== 0)
throw new Error('Delivery failed')
} catch {
logSystemMessage('warn', 'NOTIFICATIONS', 'Feishu delivery failed.')
}
})
}

export function flushFeishuQueue(timeoutMs: number): Promise<void> {
return flushQueue(queue, timeoutMs)
}
8 changes: 7 additions & 1 deletion src/logging/Notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { sendNtfy, flushNtfyQueue } from './Ntfy'
import { sendTelegram, flushTelegramQueue } from './Telegram'
import { logSystemMessage } from './LogEvent'
import type { LogColor } from './LogStyle'
import { flushFeishuQueue } from './Feishu'

export async function sendNotifications(
config: ConfigWebhook,
Expand All @@ -23,5 +24,10 @@ export async function sendNotifications(
}

export async function flushNotifications(timeoutMs: number): Promise<void> {
await Promise.allSettled([flushDiscordQueue(timeoutMs), flushNtfyQueue(timeoutMs), flushTelegramQueue(timeoutMs)])
await Promise.allSettled([
flushDiscordQueue(timeoutMs),
flushNtfyQueue(timeoutMs),
flushTelegramQueue(timeoutMs),
flushFeishuQueue(timeoutMs)
])
}
4 changes: 3 additions & 1 deletion src/logging/RunSummary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import type { AccountStats } from '../core/RunTypes'
import type { Logger } from './Logger'
import { activityKey, summarizeCompletion, summarizeRunCompletion } from '../rewards/shared/ActivityCompletion'
import { sanitizeLogMessage } from './LogMessage'
import { sendFeishuSummary } from './Feishu'

type SummaryContext = Pick<BotContext, 'logger' | 'userData' | 'activityResults' | 'accountIssues'>
type SummaryContext = Pick<BotContext, 'logger' | 'userData' | 'activityResults' | 'accountIssues' | 'config'>

export function logRunResult(
logger: Pick<Logger, 'event'>,
Expand Down Expand Up @@ -81,4 +82,5 @@ export function logAccountResult(context: SummaryContext, stats: AccountStats):
completion: stats.completion
}
)
sendFeishuSummary(context.config.webhook.feishu, stats)
}
124 changes: 124 additions & 0 deletions tests/feishu-summary.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
createFeishuCard,
createFeishuPayload,
isFeishuWebhook,
sendFeishuSummary,
flushFeishuQueue
} from '../dist/logging/Feishu.js'
import { redactSecrets } from '../src/control-api/lib.js'
import { logAccountResult } from '../dist/logging/RunSummary.js'

const detail = (label, platform, points, message = '') => ({
label,
platform,
pointsGained: points,
pointsKnown: true,
message
})
const stats = {
email: 'private@example.com',
status: 'partial',
success: false,
initialPoints: 100,
finalPoints: 125,
collectedPoints: 25,
duration: 10,
completion: {
completed: [detail('Daily set', 'desktop', 25)],
incomplete: [detail('Visual Search', 'mobile', 0, 'Not confirmed')],
unavailable: [detail('Search perk', 'desktop', 0, 'Not available')],
notApplicable: [],
counts: { completed: 1, incomplete: 1, unavailable: 1, notApplicable: 0 },
omitted: { completed: 0, incomplete: 0, unavailable: 0, notApplicable: 0 },
accountReason: null
}
}

test('partial card separates task outcomes without exposing account identity', () => {
const card = createFeishuCard(stats)
const text = JSON.stringify(card)
assert.equal(card.header.template, 'orange')
for (const value of ['Completed', 'Incomplete', 'Unavailable', 'Daily set', 'Visual Search', 'Search perk', '25'])
assert.ok(text.includes(value), value)
assert.ok(!text.includes(stats.email))
})

test('unknown points are not reported as confirmed and missing details are explicit', () => {
const card = createFeishuCard({ ...stats, status: 'failed', pointsKnown: false, completion: undefined })
const text = JSON.stringify(card)
assert.equal(card.header.template, 'red')
assert.match(text, /unknown/i)
assert.match(text, /details unavailable/i)
})

test('webhooks are restricted to Feishu and Lark bot endpoints', () => {
assert.equal(isFeishuWebhook('https://open.feishu.cn/open-apis/bot/v2/hook/abc'), true)
assert.equal(isFeishuWebhook('https://open.larksuite.com/open-apis/bot/v2/hook/abc'), true)
assert.equal(isFeishuWebhook('https://open.feishu.cn.evil.test/open-apis/bot/v2/hook/abc'), false)
assert.equal(isFeishuWebhook('http://open.feishu.cn/open-apis/bot/v2/hook/abc'), false)
})

test('signing is optional and uses the documented timestamp and secret key', () => {
const unsigned = createFeishuPayload(stats, '', '1700000000')
assert.equal('sign' in unsigned, false)
const signed = createFeishuPayload(stats, 'test-secret', '1700000000')
assert.equal(signed.sign, 'mbm4Y4oluIPQ00qlBIhX8vAZ0EKv3nw0LuTb91jPL84=')
})

test('configured delivery sends a card and API redacts credentials', async () => {
const config = {
enabled: true,
url: 'https://open.feishu.cn/open-apis/bot/v2/hook/example',
signingSecret: 'test-secret'
}
const originalFetch = globalThis.fetch
let request
globalThis.fetch = async (url, options) => {
request = { url, ...options, body: JSON.parse(options.body) }
return { ok: true, json: async () => ({ code: 0 }) }
}
try {
sendFeishuSummary(config, stats)
await flushFeishuQueue(1000)
assert.equal(request.url, config.url)
assert.equal(request.body.card.header.template, 'orange')
assert.ok(request.body.sign)
assert.deepEqual(redactSecrets({ webhook: { feishu: config } }).webhook.feishu, {
enabled: true,
url: '***REDACTED***',
signingSecret: '***REDACTED***'
})
} finally {
globalThis.fetch = originalFetch
}
})

test('account completion triggers delivery while disabled configuration does not', async () => {
const originalFetch = globalThis.fetch
let count = 0
globalThis.fetch = async () => {
count++
return { ok: true, json: async () => ({ code: 0 }) }
}
const config = { enabled: true, url: 'https://open.feishu.cn/open-apis/bot/v2/hook/example' }
const context = {
logger: { event() {} },
userData: { userName: stats.email },
activityResults: [],
accountIssues: new Map(),
config: { webhook: { feishu: config } }
}
try {
logAccountResult(context, { ...stats })
await flushFeishuQueue(1000)
assert.equal(count, 1)
config.enabled = false
logAccountResult(context, { ...stats })
await flushFeishuQueue(1000)
assert.equal(count, 1)
} finally {
globalThis.fetch = originalFetch
}
})