Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
7458cf0
chore(plans): mark slack-account-link in-progress
codeforphilly-bot Nov 29, 2026
cb66163
docs(specs): settle the gaps the Slack link and agent feed left open
codeforphilly-bot Nov 29, 2026
842bcb2
feat(shared): the Slack and applications scopes, and the Slack link o…
codeforphilly-bot Nov 29, 2026
c352bac
feat(api): index Slack links on private profiles and keep them throug…
codeforphilly-bot Nov 29, 2026
0e0df5f
feat(api): Slack linking codes, the agent's redemption, and me.slack
codeforphilly-bot Nov 29, 2026
b02dc31
feat(web): the Account screen's Slack row, and the new scopes on the …
codeforphilly-bot Nov 29, 2026
9f8f68b
docs(ops): SLACK_TEAM_ID and SLACK_OPS_BOT_DM_URL
codeforphilly-bot Nov 29, 2026
b071b21
chore(plans): mark slack-account-link done (PR #TBD)
codeforphilly-bot Nov 29, 2026
def6c53
chore(plans): mark agent-application-feed in-progress
codeforphilly-bot Nov 29, 2026
81a4167
feat(api): GET /api/agent/events, the application feed for agents
codeforphilly-bot Nov 29, 2026
e57769d
chore(plans): mark agent-application-feed done (PR #TBD)
codeforphilly-bot Nov 29, 2026
7a2bc96
chore(plans): mark agent-decide-on-behalf in-progress
codeforphilly-bot Nov 29, 2026
d9e7d3e
feat(api): the confirmation email to an admin an agent decided for
codeforphilly-bot Nov 29, 2026
264d60f
feat(api): an agent records a project admin's accept or close
codeforphilly-bot Nov 29, 2026
793a6da
test(web): "via the ops bot" on an agent-recorded decision
codeforphilly-bot Nov 29, 2026
b736889
chore(plans): mark agent-decide-on-behalf done (PR #TBD)
codeforphilly-bot Nov 29, 2026
d38155c
chore(plans): record PR #270 on the Slack-chain plans
codeforphilly-bot Nov 29, 2026
72dcd22
chore(plans): reopen slack-account-link for automatic linking
codeforphilly-bot Nov 29, 2026
5e0981d
docs(specs): link Slack accounts automatically when email and handle …
codeforphilly-bot Nov 29, 2026
28a2b5b
feat(shared): how a Slack link was made, when it was verified, and th…
codeforphilly-bot Nov 30, 2026
a680ff4
feat(api): a Slack directory client for users.lookupByEmail
codeforphilly-bot Nov 30, 2026
c4b9da3
feat(api): link Slack accounts automatically when email and handle agree
codeforphilly-bot Nov 30, 2026
fb6977d
feat(web): the Slack row says whether the link was matched automatica…
codeforphilly-bot Nov 30, 2026
7c04803
docs(ops): SLACK_BOT_TOKEN, the site's read-only Slack token
codeforphilly-bot Nov 30, 2026
b8ee18d
chore(plans): mark slack-account-link done again, with the automatic …
codeforphilly-bot Nov 30, 2026
a18bba4
chore(api): sync sheet configs with codeforphilly-data agent-grants v…
codeforphilly-bot Nov 30, 2026
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
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,18 @@ CFP_JWT_SIGNING_KEY=change-me-to-a-random-string-at-least-32-chars
# /chat + /launch redirects. Never used for our own entity ID or endpoints.
# SLACK_TEAM_HOST=codeforphilly.slack.com

# Slack workspace id (T…) the site serves. Slack account links and an agent's
# on-behalf decisions naming another workspace are refused; unset, no link can
# be made. See specs/api/slack-link.md.
# SLACK_TEAM_ID=TEXAMPLE01

# Optional: the site's own read-only Slack token (scopes users:read,
# users:read.email) for the automatic Slack link. Unset → link by code only.
# SLACK_BOT_TOKEN=xoxb-...

# Optional: a link that opens a DM with the ops bot, shown on /account.
# SLACK_OPS_BOT_DM_URL=https://codeforphilly.slack.com/app_redirect?channel=U...

# ---------------------------------------------------------------------------
# Static SPA serving (production only)
# ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion apps/api/gitsheets/agent-grants.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ root = "agent-grants"
# Public on purpose: which programs may act, with which scopes, granted by
# whom, until when. The token and its hash are never here; the hash lives in
# the site's private store. The only writer is the site.
implements = ["codeforphilly.org/agent-grants/v1"]
implements = ["codeforphilly.org/agent-grants/v2"]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"$id" = "https://codeforphilly.org/agent-grants/v1"
"$id" = "https://codeforphilly.org/agent-grants/v2"
"$schema" = "http://json-schema.org/draft-07/schema#"
required = ["createdAt", "createdBySlug", "expiresAt", "id", "label", "personSlug", "scopes"]
title = "Agent grant"
Expand Down Expand Up @@ -42,5 +42,5 @@ minItems = 1
type = "array"

[properties.scopes.items]
enum = ["moderation:read", "moderation:vote", "moderation:purge"]
enum = ["moderation:read", "moderation:vote", "moderation:purge", "slack:link", "projects:applications:read", "projects:applications:decide"]
type = "string"
4 changes: 4 additions & 0 deletions apps/api/gitsheets/contracts/sources.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
adopted = 2026-11-12T19:53:17.251Z
source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/71bf951824e93b7537025fcc1cd479cd88fb1331/contracts/codeforphilly.org/agent-grants/v1.json"

["codeforphilly.org/agent-grants/v2"]
adopted = 2026-11-30T00:52:16.731Z
source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/842bcb2c91140a1327c52ae85a55d40277404d04/contracts/codeforphilly.org/agent-grants/v2.json"

["codeforphilly.org/blog-posts/v1"]
adopted = 2026-10-14T03:31:18.13Z
source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/blog-posts/v1.json"
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ import { attachmentRoutes } from './routes/attachments.js';
import { chatRoutes } from './routes/chat.js';
import { moderationRoutes } from './routes/moderation.js';
import { agentRoutes } from './routes/agents.js';
import { slackLinkRoutes } from './routes/slack-link.js';
import { agentApplicationRoutes } from './routes/agent-applications.js';
import { webhookRoutes } from './routes/webhooks.js';
import { samlRoutes } from './routes/saml.js';
import { internalRoutes } from './routes/internal.js';
Expand Down Expand Up @@ -223,6 +225,8 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInsta
await fastify.register(chatRoutes);
await fastify.register(moderationRoutes);
await fastify.register(agentRoutes);
await fastify.register(slackLinkRoutes);
await fastify.register(agentApplicationRoutes);
await fastify.register(webhookRoutes);
await fastify.register(samlRoutes);
await fastify.register(internalRoutes);
Expand Down
24 changes: 22 additions & 2 deletions apps/api/src/auth/caller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
* Anyone who doesn't qualify gets `404 not_found`, like the rest of
* `/api/admin`: the endpoints' existence is not a signal.
*/
import type { AgentScope } from '@cfp/shared/schemas';
import { AGENT_SCOPE_REQUIRES, type AgentScope } from '@cfp/shared/schemas';
import type { FastifyRequest } from 'fastify';

import { ApiNotFoundError } from '../lib/errors.js';
import { ApiNotFoundError, UnauthenticatedError } from '../lib/errors.js';
import { agentSessionContext, type AgentPrincipal } from './agent-grant.js';
import type { SessionContext } from './middleware.js';

Expand Down Expand Up @@ -57,3 +57,23 @@ export function administratorCaller(request: FastifyRequest): SessionContext {
}
throw new ApiNotFoundError('Not found');
}

/**
* The agent on an `/api/agent/*` route: a grant carrying `scope` and every
* companion that scope requires (specs/api/agents.md → Grants). A grant
* minted before a companion rule, or a record written by hand, that lacks
* one is refused here too: the check fails closed at use, not only at mint.
* Anyone else, signed-in people and staff included, is anonymous to these
* routes → `401`.
*/
export function agentScopeCaller(
request: FastifyRequest,
scope: AgentScope,
): Extract<ModerationCaller, { kind: 'agent' }> {
const agent = request.agent;
const needed = [scope, ...(AGENT_SCOPE_REQUIRES[scope] ?? [])];
if (agent && needed.every((s) => agent.scopes.has(s))) {
return { kind: 'agent', session: agentSessionContext(agent), agent };
}
throw new UnauthenticatedError('An agent grant with this scope is required');
}
17 changes: 17 additions & 0 deletions apps/api/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,20 @@ export const EnvSchema = z.object({
* See specs/api/webhooks.md.
*/
POSTMARK_WEBHOOK_SECRET: z.string().min(16).optional(),
/**
* The Slack workspace id (`T…`) the site serves. A Slack link or an
* agent's on-behalf decision naming another workspace is refused; unset,
* no link can be made (specs/api/slack-link.md).
*/
SLACK_TEAM_ID: z.string().regex(/^T[A-Z0-9]+$/).optional(),
/**
* The site's own read-only Slack token (scopes users:read,
* users:read.email), used only for the automatic Slack link
* (specs/api/slack-link.md → Automatic link). Unset → automatic linking is off.
*/
SLACK_BOT_TOKEN: z.string().startsWith('xoxb-').optional(),
/** Optional link that opens a DM with the ops bot, for the Account screen. */
SLACK_OPS_BOT_DM_URL: z.url().optional(),
});

export type Env = z.infer<typeof EnvSchema>;
Expand Down Expand Up @@ -159,6 +173,9 @@ export const envJsonSchema = {
POSTMARK_SERVER_TOKEN: { type: 'string' },
POSTMARK_MESSAGE_STREAM: { type: 'string', default: 'outbound' },
POSTMARK_WEBHOOK_SECRET: { type: 'string', minLength: 16 },
SLACK_TEAM_ID: { type: 'string', pattern: '^T[A-Z0-9]+$' },
SLACK_BOT_TOKEN: { type: 'string', pattern: '^xoxb-' },
SLACK_OPS_BOT_DM_URL: { type: 'string', pattern: '^https://' },
CFP_NOTIFICATION_FROM: {
type: 'string',
default: 'Code for Philly <notifications@codeforphilly.org>',
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,11 @@ export class ForbiddenError extends Error {

/** Thrown when a resource is not found (404). */
export class ApiNotFoundError extends Error {
constructor(message = 'Not found') {
readonly code: string;
constructor(message = 'Not found', code = 'not_found') {
super(message);
this.name = 'ApiNotFoundError';
this.code = code;
}
}

Expand Down Expand Up @@ -144,7 +146,7 @@ export function mapError(
}

if (err instanceof ApiNotFoundError) {
void reply.code(404).send(errorResponse('not_found', err.message, traceId));
void reply.code(404).send(errorResponse(err.code, err.message, traceId));
return;
}

Expand Down
11 changes: 11 additions & 0 deletions apps/api/src/notify/email-notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
EventReminderNotification,
EventRsvpNotification,
EventUpdatedNotification,
AgentDecisionConfirmation,
ApplicationDecisionNotification,
MemberAddedNotification,
NewApplicationNotification,
Expand All @@ -34,6 +35,7 @@ import {
renderWelcomeEmail,
} from './templates.js';
import {
renderAgentDecisionConfirmationEmail,
renderApplicationDecisionEmail,
renderMemberAddedEmail,
renderNewApplicationEmail,
Expand Down Expand Up @@ -92,6 +94,15 @@ export class EmailNotifier implements Notifier {
return this.#deliver('application notice', ctx, n.email, renderNewApplicationEmail(n, this.#siteHost));
}

async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> {
const ctx = { kind: `application.agent-${n.decision}`, project: n.projectSlug };
if (!n.email) {
this.#log.warn(ctx, 'agent decision confirmation: no email address; skipped');
return { delivered: false };
}
return this.#deliver('agent decision confirmation', ctx, n.email, renderAgentDecisionConfirmationEmail(n, this.#siteHost));
}

async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> {
const ctx = { kind: `application.${n.outcome}`, project: n.projectSlug };
if (!n.email) {
Expand Down
23 changes: 23 additions & 0 deletions apps/api/src/notify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,25 @@ export interface ApplicationDecisionNotification {
readonly chatChannel: string | null;
}

/**
* To a project admin: an agent recorded a decision in their name
* (specs/behaviors/authorization.md → On behalf of a project admin), so a
* decision they did not make surfaces at once.
*/
export interface AgentDecisionConfirmation {
readonly email: string;
/** The admin's name. */
readonly fullName: string;
readonly projectTitle: string;
readonly projectSlug: string;
readonly applicantName: string;
readonly decision: 'accepted' | 'closed';
/** The agent account's name, e.g. "Example Ops Bot". */
readonly agentName: string;
}

export interface Notifier {
notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }>;
notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }>;
notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }>;
notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>;
Expand Down Expand Up @@ -193,6 +211,11 @@ export class LoggingNotifier implements Notifier {
return { delivered: true };
}

async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> {
this.#log.info({ kind: `application.agent-${n.decision}`, project: n.projectSlug }, 'agent decision confirmation');
return { delivered: true };
}

async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> {
// Never the note: it is emailed and stored nowhere, logs included.
this.#log.info({ kind: `application.${n.outcome}`, project: n.projectSlug }, 'application decision notification');
Expand Down
29 changes: 29 additions & 0 deletions apps/api/src/notify/membership-templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* never turned into a link by us.
*/
import type {
AgentDecisionConfirmation,
ApplicationDecisionNotification,
MemberAddedNotification,
NewApplicationNotification,
Expand Down Expand Up @@ -197,3 +198,31 @@ export function renderApplicationDecisionEmail(n: ApplicationDecisionNotificatio
footer,
);
}

/**
* To the project admin an agent named: "The ops bot recorded that you
* accepted …", with a link to the Applications screen, so a decision they
* did not make surfaces at once (authorization.md → On behalf of a project admin).
*/
export function renderAgentDecisionConfirmationEmail(n: AgentDecisionConfirmation, siteHost: string): MembershipEmail {
const verb = n.decision === 'accepted' ? 'accepted' : 'closed';
const what =
n.decision === 'accepted'
? `accepted ${n.applicantName}'s application to ${n.projectTitle}; they are now a member`
: `closed ${n.applicantName}'s application to ${n.projectTitle}; they are still following the project`;
return renderBlocks(
`The ops bot recorded that you ${verb} an application to ${n.projectTitle}`,
[
{ p: `Hi ${n.fullName}, the ops bot (${n.agentName}) recorded in your name that you ${what}.` },
{
p:
"If you didn't say so, tell the organizers. " +
(n.decision === 'accepted'
? 'You can undo it by removing the member from the project.'
: 'You can undo it by adding the person to the project directly.'),
},
{ link: `${projectUrl(siteHost, n.projectSlug)}/applications`, label: 'Open the Applications screen' },
],
`You're receiving this because you are an admin of ${n.projectTitle} and your Slack account is linked to Code for Philly.`,
);
}
3 changes: 3 additions & 0 deletions apps/api/src/plugins/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ const CREDENTIAL_PATHS = [
'/api/auth/link-github',
'/api/auth/password-reset/',
'/api/account-claim/by-password',
// The Slack linking pair mints and accepts a one-time code (slack-link.md).
'/api/account/slack-link/code',
'/api/agent/slack-links',
];

function pathOf(url: string): string {
Expand Down
29 changes: 28 additions & 1 deletion apps/api/src/plugins/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ import { ServerClient } from 'postmark';
import { FollowerMailer } from '../services/follower-mail.js';
import { ProjectApplicationService } from '../services/project-application.js';
import { ApplicationNotices } from '../services/application-notices.js';
import { SlackLinkService } from '../services/slack-link.js';
import { AgentFeedService } from '../services/agent-feed.js';
import { AgentDecisionService } from '../services/agent-decision.js';
import { SlackAutoLinkService } from '../services/slack-auto-link.js';
import { FetchSlackDirectory } from '../slack/directory.js';

declare module 'fastify' {
interface FastifyInstance {
Expand Down Expand Up @@ -74,6 +79,10 @@ declare module 'fastify' {
agents: AgentService;
agentPurge: AgentPurgeService;
spamPurges: SpamPurgeLogService;
slackLinks: SlackLinkService;
agentFeed: AgentFeedService;
agentDecisions: AgentDecisionService;
slackAutoLink: SlackAutoLinkService;
};
/** Shared in-memory state — write routes call StateApply.apply against this. */
inMemoryState: InMemoryState;
Expand Down Expand Up @@ -139,6 +148,14 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> {
);

const githubAccount = new GitHubAccountService(state);
const applications = new ProjectApplicationService(state, fastify.store.private);
// The automatic Slack link (slack-link.md → Automatic link): off without the site's own token.
const slackAutoLink = new SlackAutoLinkService(state, fastify.store.private, {
teamId: fastify.config.SLACK_TEAM_ID,
directory: fastify.config.SLACK_BOT_TOKEN ? new FetchSlackDirectory(fastify.config.SLACK_BOT_TOKEN) : null,
log: fastify.log,
});
fastify.addHook('onClose', async () => slackAutoLink.close());
fastify.decorate('services', {
projects: new ProjectService(state, fts, fastify.store.private),
people: new PersonService(state, fts, fastify.store.private),
Expand All @@ -153,7 +170,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> {
eventSeriesWrite: new EventSeriesWriteService(state),
projectsWrite: new ProjectWriteService(state),
projectMembershipsWrite: new ProjectMembershipWriteService(state),
applications: new ProjectApplicationService(state, fastify.store.private),
applications,
projectUpdatesWrite: new ProjectUpdateWriteService(state),
projectBuzzWrite: new ProjectBuzzWriteService(state),
helpWantedWrite: new HelpWantedWriteService(state),
Expand Down Expand Up @@ -198,6 +215,16 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> {
webUrl: dataRepoWebUrl(fastify.config.CFP_DATA_REMOTE),
branch: fastify.config.CFP_DATA_BRANCH ?? 'published',
}),
slackLinks: new SlackLinkService(state, fastify.store.private, {
teamId: fastify.config.SLACK_TEAM_ID,
botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL,
}),
agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID, autoLink: slackAutoLink }),
agentDecisions: new AgentDecisionService(state, fastify.store.private, applications, {
teamId: fastify.config.SLACK_TEAM_ID,
autoLink: slackAutoLink,
}),
slackAutoLink,
});
}

Expand Down
Loading