diff --git a/backend/domain.js b/backend/domain.js index 819e1b2..be05dce 100644 --- a/backend/domain.js +++ b/backend/domain.js @@ -136,7 +136,7 @@ export function domain(store, baseCatalog, origin) { publishedAt: published?.publishedAt || nowISO(), revision }); // Queue an approval email. The address is looked up from Auth at send time, never stored here. - if (decision === 'publish') tx.set('mailOutbox', id + '-r' + revision, {kind: 'tool-approved', toolId: id, name: row.data.name, + if (decision === 'publish') tx.set('mailOutbox', id + '-r' + revision, {kind: 'tool-approved', toolId: id, name: row.data.name, author: row.author, ownerUid: row.ownerUid, url: origin + '/tools/' + id + '/', update: Boolean(published), status: 'pending', createdAt: nowISO()}); return row; }); diff --git a/backend/mailer.js b/backend/mailer.js new file mode 100644 index 0000000..e6a2314 --- /dev/null +++ b/backend/mailer.js @@ -0,0 +1,75 @@ +// Sends queued approval emails through Microsoft Graph (app-only, Mail.Send limited to one mailbox). +// Each record is claimed in a transaction first, so parallel instances never send the same mail twice. +import { nowISO } from './domain.js'; + +export function approvalMessage({name, url, author, update}) { + const subject = update ? `Your ToolIndex listing update is live: ${name}` : `Your tool is live on ToolIndex: ${name}`; + const opening = update ? `Your update to ${name} has been reviewed and is now live on ToolIndex:` : `Good news: ${name} has been reviewed and is now listed on ToolIndex:`; + const body = [ + `Hi ${author || 'there'},`, '', opening, url, '', + 'Thank you for sharing it. People and their agents can now find it, see how to set it up, and go straight to your source.', '', + 'If the tool changes, you can edit the listing from your account at https://toolindex.org/account/. Edits are reviewed again, and the current version stays visible in the meantime.', '', + 'Thanks,', 'ToolIndex', 'https://toolindex.org' + ].join('\n'); + return {subject, body}; +} + +export function mailer({store, auth, env = process.env, fetchImpl = fetch, log = console}) { + const config = {tenant: env.MAIL_TENANT_ID, client: env.MAIL_CLIENT_ID, secret: env.MAIL_CLIENT_SECRET, sender: env.MAIL_SENDER}; + const enabled = Boolean(config.tenant && config.client && config.secret && config.sender); + let token = null; + + async function accessToken() { + if (token && token.expires > Date.now() + 60000) return token.value; + const res = await fetchImpl(`https://login.microsoftonline.com/${encodeURIComponent(config.tenant)}/oauth2/v2.0/token`, { + method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({client_id: config.client, client_secret: config.secret, scope: 'https://graph.microsoft.com/.default', grant_type: 'client_credentials'}) + }); + if (!res.ok) throw new Error('Mail sign-in failed: ' + res.status); + const data = await res.json(); + token = {value: data.access_token, expires: Date.now() + (data.expires_in || 3600) * 1000}; + return token.value; + } + + async function send(to, {subject, body}) { + const res = await fetchImpl(`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(config.sender)}/sendMail`, { + method: 'POST', headers: {Authorization: 'Bearer ' + await accessToken(), 'Content-Type': 'application/json'}, + body: JSON.stringify({message: {subject, body: {contentType: 'Text', content: body}, toRecipients: [{emailAddress: {address: to}}]}, saveToSentItems: true}) + }); + if (!res.ok) throw new Error('Mail send failed: ' + res.status); + } + + async function claim(key) { + return store.atomic(async tx => { + const row = await tx.get('mailOutbox', key); + if (!row || row.status !== 'pending') return null; + tx.set('mailOutbox', key, {...row, status: 'sending', claimedAt: nowISO()}); + return row; + }); + } + const finish = (key, row, fields) => store.atomic(async tx => tx.set('mailOutbox', key, {...row, ...fields})); + + return { + enabled, + // Sends up to `limit` pending approval emails. Never throws; failures stay visible on the record. + async flush(limit = 20) { + if (!enabled) return {sent: 0, skipped: 'not configured'}; + let sent = 0; + for (const {_key} of await store.list('mailOutbox', {filters: [['status', 'pending']], limit})) { + const row = await claim(_key); + if (!row) continue; + try { + const user = await auth.getUser(row.ownerUid); + if (!user.email || !user.emailVerified) { await finish(_key, row, {status: 'skipped', note: 'No verified email', finishedAt: nowISO()}); continue; } + await send(user.email, approvalMessage(row)); + await finish(_key, row, {status: 'sent', sentAt: nowISO()}); sent++; + } catch (err) { + const attempts = (row.attempts || 0) + 1; + await finish(_key, row, {status: attempts >= 5 ? 'failed' : 'pending', attempts, lastError: String(err.message).slice(0, 200), lastTriedAt: nowISO()}); + log.error('Approval mail failed', _key, String(err.message).slice(0, 200)); + } + } + return {sent}; + } + }; +} diff --git a/backend/package-lock.json b/backend/package-lock.json index 77f0dd7..fdb7f92 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -12,6 +12,7 @@ "express": "5.3.0", "express-rate-limit": "8.7.1", "firebase-admin": "14.5.0", + "google-auth-library": "11.3.2", "zod": "^4.0.0" }, "engines": { diff --git a/backend/package.json b/backend/package.json index 2676e9e..95bb36f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -15,6 +15,7 @@ "express": "5.3.0", "express-rate-limit": "8.7.1", "firebase-admin": "14.5.0", + "google-auth-library": "11.3.2", "zod": "^4.0.0" } } diff --git a/backend/server.js b/backend/server.js index 85c7dee..fc9f4f5 100644 --- a/backend/server.js +++ b/backend/server.js @@ -13,6 +13,8 @@ import { z } from 'zod'; import { FirestoreStore } from './store.js'; import { domain, Problem, toolSchema, profileSchema } from './domain.js'; import { oauthProvider, SCOPES } from './oauth.js'; +import { mailer } from './mailer.js'; +import { OAuth2Client } from 'google-auth-library'; import { page, card, detail, markdownTool, profileContent, accountContent, esc } from './render.js'; const here = path.dirname(fileURLToPath(import.meta.url)); @@ -25,6 +27,11 @@ export async function createApp(options = {}) { const auth = options.auth || getAuth(), store = options.store || new FirestoreStore(); const api = domain(store, baseCatalog, origin); const provider = oauthProvider(store, origin, uid => auth.getUser(uid)); + const mail = options.mail || mailer({store, auth}); + // The daily review digest signs in as one Google service account that has no IAM roles. It can only read this queue. + const automationAccount = (options.automationAccount ?? process.env.AUTOMATION_SERVICE_ACCOUNT ?? '').toLowerCase(); + const googleTokens = new OAuth2Client(); + const verifyAutomation = options.verifyAutomation || (async idToken => (await googleTokens.verifyIdToken({idToken, audience: origin + '/api/automation'})).getPayload()); const admins = new Set((options.admins || process.env.ADMIN_EMAILS || '').split(',').map(s=>s.trim().toLowerCase()).filter(Boolean)); const signInProviders=(options.signInProviders || process.env.SIGN_IN_PROVIDERS || '').split(',').filter(p=>['google.com','github.com'].includes(p)); const allowedOrigins = new Set([origin, 'https://toolindex-org.web.app', 'https://toolindex-org.firebaseapp.com']); @@ -35,7 +42,7 @@ export async function createApp(options = {}) { res.set({'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin', 'Permissions-Policy':'camera=(), microphone=(), geolocation=()', 'Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.gstatic.com/firebasejs/13.1.0/ https://apis.google.com; style-src 'self'; img-src 'self' https:; font-src 'self'; connect-src 'self' https://identitytoolkit.googleapis.com https://securetoken.googleapis.com; frame-src https://toolindex-org.firebaseapp.com https://apis.google.com; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"}); - if (req.path.startsWith('/account') || req.path.startsWith('/authorize') || req.path.startsWith('/api/account') || req.path.startsWith('/api/me') || req.path.startsWith('/api/review')) res.set({'Cache-Control':'private, no-store','X-Robots-Tag':'noindex, nofollow'}); + if (req.path.startsWith('/account') || req.path.startsWith('/authorize') || req.path.startsWith('/api/account') || req.path.startsWith('/api/me') || req.path.startsWith('/api/review') || req.path.startsWith('/api/automation')) res.set({'Cache-Control':'private, no-store','X-Robots-Tag':'noindex, nofollow'}); next(); }); app.use(express.json({limit:'32kb'})); @@ -81,7 +88,19 @@ export async function createApp(options = {}) { app.post('/api/me/tools/:id/withdraw',sameOrigin,session,async(req,res)=>json(res,await api.withdraw(req.user,checkedId(req.params.id)))); app.delete('/api/me/connections/:id',sameOrigin,session,async(req,res)=>{await provider.revokeGrant(req.user,z.string().max(100).parse(req.params.id));json(res,{ok:true});}); app.get('/api/review',session,reviewer,async(req,res)=>json(res,{submissions:await api.queue()})); - app.post('/api/review/:id',sameOrigin,session,reviewer,async(req,res)=>json(res,await api.review(req.user,checkedId(req.params.id),z.number().int().positive().parse(req.body.revision),req.body.decision,req.body.evidence))); + app.post('/api/review/:id',sameOrigin,session,reviewer,async(req,res)=>{ + const row=await api.review(req.user,checkedId(req.params.id),z.number().int().positive().parse(req.body.revision),req.body.decision,req.body.evidence); + if(row.status==='published')await mail.flush(); + json(res,row); + }); + app.get('/api/automation/review-queue',async(req,res)=>{ + const raw=(req.get('authorization')||'').replace(/^Bearer\s+/i,''); + let who=null; + try{if(automationAccount&&raw)who=await verifyAutomation(raw);}catch{} + if(!who||!who.email_verified||String(who.email).toLowerCase()!==automationAccount)return res.status(401).set('Cache-Control','no-store').json({error:'Automation access required'}); + const outbox=await store.list('mailOutbox',{limit:200}); + json(res,{submissions:(await api.queue()).map(({ownerUid,...s})=>s),approvalMail:{pending:outbox.filter(m=>m.status==='pending').length,failed:outbox.filter(m=>m.status==='failed').length}}); + }); app.get('/api/account/consent/:id',session,async(req,res)=>json(res,await provider.pending(z.string().max(100).parse(req.params.id)))); app.post('/api/account/consent/:id',sameOrigin,session,async(req,res)=>json(res,{redirect:await provider.consent(req.user,z.string().max(100).parse(req.params.id),z.boolean().parse(req.body.allow))})); @@ -208,9 +227,9 @@ export async function createApp(options = {}) { if(status>=500)console.error('Request failed',req.method,req.path,err.code||err.name); res.status(status).set('Cache-Control','no-store').json({error:message}); }); - return {app,api,provider}; + return {app,api,provider,mail}; } if(process.argv[1] && path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) { - const {app}=await createApp();const port=Number(process.env.PORT || 8080); - app.listen(port,'0.0.0.0',()=>console.log('ToolIndex listening on port '+port)); + const {app,mail}=await createApp();const port=Number(process.env.PORT || 8080); + app.listen(port,'0.0.0.0',()=>{console.log('ToolIndex listening on port '+port);mail.flush().then(r=>r.sent&&console.log('Sent '+r.sent+' queued approval emails'));}); } diff --git a/backend/test/mail.test.js b/backend/test/mail.test.js new file mode 100644 index 0000000..147e27c --- /dev/null +++ b/backend/test/mail.test.js @@ -0,0 +1,75 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { MemoryStore } from '../store.js'; +import { domain } from '../domain.js'; +import { mailer, approvalMessage } from '../mailer.js'; +import { createApp } from '../server.js'; + +const origin = 'https://toolindex.example'; +const alice = {uid: 'alice', email: 'alice@example.test', email_verified: true, admin: false}; +const admin = {uid: 'admin', email: 'reviewer@example.test', email_verified: true, admin: true}; +const profile = {handle: 'alice-tools', displayName: 'Alice', bio: '', website: '', avatar: '', discoverable: true}; +const tool = {name: 'Example tool', summary: 'A focused example for agents.', type: 'CLI', category: 'Coding', repository: 'https://example.org/docs', version: '1.0', license: 'MIT', installation: 'Install the complete package.'}; +const env = {MAIL_TENANT_ID: 'tenant', MAIL_CLIENT_ID: 'client', MAIL_CLIENT_SECRET: 'secret', MAIL_SENDER: 'hello@toolindex.example'}; + +async function publishedTool(store) { + const api = domain(store, {listings: []}, origin); + await api.saveProfile(alice, profile); + const d = await api.saveTool(alice, tool); await api.submit(alice, d.id, d.revision); + await api.review(admin, d.id, d.revision, 'publish', 'Reviewed package scope'); + return d; +} +function fakeGraph({failSend = false} = {}) { + const sent = []; + const fetchImpl = async (url, init) => { + if (url.includes('/oauth2/v2.0/token')) return {ok: true, json: async () => ({access_token: 'token', expires_in: 3600})}; + if (failSend) return {ok: false, status: 503}; + sent.push({url, message: JSON.parse(init.body).message}); return {ok: true}; + }; + return {sent, fetchImpl}; +} +const auth = {getUser: async uid => uid === 'alice' ? {uid, email: alice.email, emailVerified: true} : {uid, email: '', emailVerified: false}}; + +test('approval email goes once to the verified submitter, from the configured mailbox', async () => { + const store = new MemoryStore(); await publishedTool(store); + const graph = fakeGraph(), m = mailer({store, auth, env, fetchImpl: graph.fetchImpl, log: {error() {}}}); + assert.deepEqual(await m.flush(), {sent: 1}); + assert.deepEqual(await m.flush(), {sent: 0}); + assert.equal(graph.sent.length, 1); + assert.ok(graph.sent[0].url.endsWith('/users/hello%40toolindex.example/sendMail')); + assert.equal(graph.sent[0].message.toRecipients[0].emailAddress.address, alice.email); + assert.match(graph.sent[0].message.subject, /Example tool/); + assert.match(graph.sent[0].message.body.content, /https:\/\/toolindex\.example\/tools\//); + const [row] = await store.list('mailOutbox'); assert.equal(row.status, 'sent'); assert.ok(!JSON.stringify(row).includes(alice.email)); +}); + +test('mail stays queued when not configured or when sending fails', async () => { + const store = new MemoryStore(); await publishedTool(store); + assert.equal((await mailer({store, auth, env: {}}).flush()).skipped, 'not configured'); + const m = mailer({store, auth, env, fetchImpl: fakeGraph({failSend: true}).fetchImpl, log: {error() {}}}); + await m.flush(); + const [row] = await store.list('mailOutbox'); assert.equal(row.status, 'pending'); assert.equal(row.attempts, 1); +}); + +test('approval text has no placeholders or em dashes', () => { + for (const update of [false, true]) { + const {subject, body} = approvalMessage({name: 'Tool', url: 'https://toolindex.org/tools/tool/', author: 'alice', update}); + assert.ok(!/[—\[\]]/.test(subject + body)); + } +}); + +test('review queue endpoint only answers the one automation service account', async t => { + const store = new MemoryStore(); const api = domain(store, {listings: []}, origin); + await api.saveProfile(alice, profile); const d = await api.saveTool(alice, tool); await api.submit(alice, d.id, d.revision); + const tokens = {good: {email: 'digest@project.iam.gserviceaccount.com', email_verified: true}, other: {email: 'someone@example.test', email_verified: true}}; + const {app} = await createApp({store, auth: {}, origin, catalog: {listings: []}, automationAccount: 'digest@project.iam.gserviceaccount.com', + verifyAutomation: async token => { if (!tokens[token]) throw Error('bad'); return tokens[token]; }}); + const server = app.listen(0, '127.0.0.1'); await once(server, 'listening'); t.after(() => new Promise(r => server.close(r))); + const url = 'http://127.0.0.1:' + server.address().port + '/api/automation/review-queue'; + for (const token of [null, 'bad', 'other']) assert.equal((await fetch(url, token ? {headers: {Authorization: 'Bearer ' + token}} : {})).status, 401); + const res = await fetch(url, {headers: {Authorization: 'Bearer good'}}); assert.equal(res.status, 200); + const body = await res.json(); assert.equal(body.submissions.length, 1); assert.equal(body.submissions[0].id, d.id); + assert.ok(!JSON.stringify(body).includes('alice@') && !body.submissions[0].ownerUid); + assert.match(res.headers.get('cache-control'), /no-store/); assert.match(res.headers.get('x-robots-tag'), /noindex/); +}); diff --git a/scripts/stage_cloudrun.py b/scripts/stage_cloudrun.py index 80d88ed..31023ec 100644 --- a/scripts/stage_cloudrun.py +++ b/scripts/stage_cloudrun.py @@ -14,7 +14,7 @@ def stage(root=ROOT): for filename in ('Dockerfile',): shutil.copy2(root / 'deploy/cloudrun' / filename, target / filename) (target / 'backend').mkdir() - for filename in ('package.json', 'package-lock.json', 'store.js', 'domain.js', 'oauth.js', 'render.js', 'server.js'): + for filename in ('package.json', 'package-lock.json', 'store.js', 'domain.js', 'oauth.js', 'render.js', 'server.js', 'mailer.js'): shutil.copy2(root / 'backend' / filename, target / 'backend' / filename) shutil.copy2(root / 'site/layout.html', target / 'layout.html') # A fresh build prevents unrelated files left in a previous dist from shipping.