mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-04 02:32:07 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connections provide governed tools, chat channels, model accounts,
and gateways.
> - Several management routes require a human board actor even when an
agent has the required grant.
> - Default agents must configure these resources within the responsible
user's authority.
> - This pull request adds a shared authorization path to the existing
REST and native API surface.
> - Human authentication, execution approvals, and local host boundaries
remain enforced.
> - The benefit is that a standard agent can complete authorized setup
with a bounded human handoff.
## Linked Issues or Issue Description
**Subsystem affected**
Server authorization, connection services, shared contracts, native API
discovery, database schema.
**Problem or motivation**
Connection administration is available in the web app but often
unavailable to agents. Agent grants, responsible-user authority,
credential ownership, and actor attribution need separate checks.
Opening gateway-token creation also requires preserving the issuing
agent's delegated authority during token use.
**Proposed solution**
Use the existing authorization evaluator for every connection family.
Enforce current responsible-user authority, effective trust, grant
scope, resource visibility, and target-agent access. Keep existing agent
grants unchanged. Expose authorized configuration through default
`search_api` and `call_api`. Save human authentication steps and let
agents continue after completion.
**Roadmap alignment**
This change completes the API access path for the existing Connected
Apps, Personal & Shared AI Accounts, and governed MCP Gateway
capabilities in `ROADMAP.md`. It follows the maintainer's requested
design. Related work: #11899 enforces connection execution access and
creator/manager rules; this PR extends agent management across
connection families. It does not replace that execution-policy work.
## What Changed
- Add shared connection management context and mandatory
responsible-user, trust, scope, and target checks.
- Allow authorized agents to configure tool, chat/email, GitHub/Slack,
AI, profile, and gateway resources through existing routes.
- Preserve human credential ownership and record the actual agent,
responsible user, and run or key in audit data.
- Preserve saved browser authentication handoffs and callback session
checks.
- Bind agent-issued durable gateway tokens to their responsible user and
recheck delegated authority at use.
- Add explicit REST transport and management capability metadata,
built-in guidance, and sensitive-response handling.
- Intersect caller and endpoint-agent Slack test/invitation policies,
including independent and shared rates. Require the addressed human’s
current endpoint identity link before completing identity handoffs.
- Add production-authenticated integration scenarios. Companion #17739
contains the saved setup UI (including the required human
import/rotation step), product and permission documentation,
catalog/Vercel credential and callback ownership, and operation maps to
keep each review below 100 files. Both PRs must ship together; merge
this implementation first, then its companion.
## Verification
- Current implementation head:
`2ecd6451d0d0c8d82121a4e3fa4ce94c5befbbd6`, including master
`ea727dc3c2`, 99 files. The latest follow-up fixes the two valid
findings from the preceding f9 review. Exact-head Greptile has completed
at5/5 with no findings and Superagent passed. Full exact-head Linux CI
workflow40446606056 completed SUCCESS; only the queued external
Paperclip Review remains pending; earlier Linux passes do not qualify
this successor.
- Latest preserved-stack verification passed **2,165 tests** in fresh
PostgreSQL: **70 actual-auth scenarios**, 27 OpenAPI contracts, 2,022
native API tests and 46 saved GitHub wizard cases. **141 existing
gateway/policy acceptance tests** also passed. Workspace
typecheck/build, maps and token gates passed. The first workspace
typecheck was blocked by sandbox tsx IPC permissions; its authorized
rerun passed. This is focused local evidence; the full Linux CI matrix
is still required.
- Issuer/target gateway policy regressions were red before the fix. Both
decisions now intersect, including Block/Ask first/rates, same
credential identity and current token/user/agent authority after
approval. Invocations retain their token and actual requesting agent;
deleted tokens fail closed. Thirteen actual-auth cases cover revocation,
narrowed scope, approvals, shared rates and board compatibility.
Intermediate missing-token attribution, review-context and
implicit-session actor failures remain in the qualification record; all
final cases pass.
- Activity pagination now retains a bounded cursor across private-only
windows. The actual-JWT regression reaches three older readable events
after 27 private ones without exposing private details. A native
device-login regression was red for plaintext receipts; local check and
test-call results now use existing protected-response handling. The
passing actual-auth case proves encrypted persistence, exact replay,
redacted history and no response asset.
- Previous-head `5b55195593` Linux CI initially failed e2e shard 4/8 in
the existing connection-intent continuation test: periodic recovery
queued a repair at 01:21:47, the scripted journey completed the task at
01:21:48, and the extra queued run was cancelled at 01:21:49 because the
task was terminal. The assertion selected that latest cancelled run.
GitHub refused the first attempt while the workflow was nonterminal.
After completion, the single evidence-supported failed-job rerun was
accepted as **attempt 2** on the same head (workflow 40431202466). The
failed shard and final E2E aggregate passed on attempt 2, and the
complete Linux workflow for that head is successful. The original
failure remains part of qualification. No additional unchanged-code
rerun will be used for this failure.
- Companion CI also has an unchanged login-cleanup idleness timeout,
retained in its qualification record. That same 16-case suite passed in
this parent Linux run and a fresh local database. Both preceding
workflows passed after their single failed-job reruns as attempt 2; the
original failures remain recorded. No additional unchanged-code rerun
was used.
- Migration `0380_broken_aqueduct.sql` was regenerated through the
repository workflow after master took 0379 for project Git
authorization. It adds the responsible-user column with `IF NOT EXISTS`,
preserves upstream migrations, and satisfies snapshot retention and
migration safety checks.
- Upstream published Copilot v62 and v63 identities remain byte-for-byte
unchanged. The combined guidance is now v64, digest
`sha256:22e31f95ef972bcead98a4a707c9f33433558fd111e390e027a2bbb4346e112a`.
The normal shared TypeScript/Rust identity check and **61 Copilot
installation tests passed**. The old source-identity assertion first
failed against unchanged published v63; regenerating a new v64 preserves
the published release.
- Workspace `pnpm -r typecheck` and `pnpm build`, map validation, and UI
token gates passed on the final combined stack after the upstream merge.
Node 24.22.1 / pnpm 9.15.4 were used.
- **Earlier 82 API/OpenAPI tests passed** in fresh PostgreSQL 18: 55
assembled-server scenarios and 27 contracts. They use real persistent
agent keys, run JWTs, human sessions, production defaults, and
deterministic provider fixtures. No actor injection establishes access.
- The new email regression was red before per-account scope filtering.
The Arcade regression was red before human ownership and inventory-key
fixes; it also verifies actual-agent audit identity and a human-session
inventory read. The activity regression measured **200 authorization
checks before the fix and one afterward** for the same one-item page.
- **82 GitHub UI tests passed**, including all three new
failed-replacement regressions that were red before their fix. The UI
preserves an earlier copy only after confirming its committed
generation. Changed or unreadable results block copying and reconnecting
until reconciled. Human-only secret responses now include their
nonsecret committed generation.
- Private test status now rechecks the originating principal and linked
task, including mandatory agent/responsible-user privacy. Cross-agent
tests require the full caller tool access decision and the same
credential identity, regardless of auth label; caller and target
policies/approvals and rate limits apply before execution and after
human approval. A profile-only precondition was found to reject valid
allow-policy and scoped-grant access and has been removed. Both
permitted-access cases and a no-auth-label identity regression were red
before the correction; caller-specific Block still prevents provider
execution. The private-status regression was also red before its fix.
- The tool-activity regression measured 100 capability decisions and 102
run captures on a 100-event page before the fix. It now uses two task
decisions and at most two captures while retaining the same 50 visible
events, private-event filtering, and 403 after audit-grant revocation.
The regression was red before request-context reuse and task-decision
sharing; final server typecheck/build also pass.
- Generic chat configure/reconnect now hands agent-supplied verification
credentials to the addressed human before provider work or vault
changes. Actual key/JWT regressions were red for Slack signing-key
replacement and generic channel secret-reference rebinding. They now
prove unchanged refs and vaulted signing value, human setup, permitted
agent bot-token repair, and governed test messages. All 82 API/OpenAPI
cases pass in fresh PostgreSQL. Eight native receipt protections and
final server typecheck/build also pass.
- The preceding review found that old healthy state could retire a
credential-entry card before a human changed anything. The actual-JWT
regression was red. Saved field generations now change only with
protected values and commit with refs plus a verification fence; retries
retain the baseline. Old health, bot-token repair and unchanged entry
stay pending. New signing verification and current authority permit
continuation. A separate red race proved that user revocation during
provider authentication could return 403 after refs changed; authority
is now checked before persistence and inside the credential transaction.
The final 82 API/OpenAPI cases, four neighboring real-database
Slack/GitHub lifecycle cases, and final server typecheck/build pass.
- A preceding full run crossed a rate-window boundary. Database rows
prove one consumed slot at 23:35 and another at 23:36 for the same
policy/bucket. Only Date is frozen in the rate test cases; transport and
asynchronous timers remain real. Production rate behavior is unchanged,
and the final full run passes. An intermediate fixture failure that
overwrote hidden generation metadata with an API projection is retained
in the qualification record.
- Linux CI on an earlier head found two rate-admission assertions that
omitted the newly persisted bucket key. The failures were reproduced
locally; both assertions now verify the exact actor/tool bucket and all
49 policy-service tests pass. The companion qualification record retains
the initial and intermediate failures. Catalog creator attribution is
preserved in the companion to keep this implementation review at 99
files.
- The latest review reproduced three regressions before repair: complete
human replacements failed on unavailable old signing secrets, fresh
GitHub links incorrectly selected reconnect, and different
credential-entry requests shared an idempotency key. Each old protected
ref now has a narrow known-unavailable fallback; unexpected resolver
failures and company/scope violations still abort. Fresh imports keep
their credential form, configured endpoints keep reconnect, and
canonical field sets/completion modes distinguish handoffs while
matching retries retain their baseline. All 55 actual-auth scenarios and
27 separately run OpenAPI contracts pass, as do server typecheck/build.
Companion #17739 also passes all 41 wizard tests including actual
fresh-form submission, UI typecheck, maps and token gates. Earlier red
results and a mistyped OpenAPI filename are retained in qualification.
- The configured GitHub handoff regression was red in the
browser-component tests and actual-auth link/persistence tests. Saved
links now name requested fields and all/any completion mode; the
companion form submits those supplied fields through reconnect and
retains other saved credentials. Webhook/client-secret reconnect remains
human-only; first-setup secret restrictions remain. All 46 wizard tests
pass, including combined modes and legacy links. A duplicate review
referenced the older companion bf760912; the current form is already
fixed, linked in the reply, and its thread is resolved.
- Linux CI on bf760912 failed automatic Slack provisioning because vault
persistence cleared an already verified manifest-update challenge. The
same regression was reproduced locally. The provider-owned helper now
preserves proof only for the current signing fingerprint and callback
URL. Eight existing compatibility cases pass, including this case and
initial GitHub secret rejection. The first uncommitted GitHub-field
variant also failed that initial boundary and was narrowed to reconnect;
both failures remain in qualification.
- The upstream merge conflicted only in generated migration metadata.
Upstream 0379 is preserved, normal generation/pruning produced 0380, and
two repeated applications of the idempotent additive SQL passed. The
final combined stack passed **128 tests** (55 actual-auth, 27 OpenAPI
and 46 wizard cases) in fresh PostgreSQL. Eight Google UI cases also
pass; the two protocol cases could not initialize embedded PostgreSQL in
this fresh local attempt. Their earlier passing evidence remains
historical; fresh Linux CI must execute them. Vercel personal credential
attribution is preserved in companion #17739 with its other
ownership/consent follow-ups, keeping this PR at 99 files.
- The suite covers fresh defaults, restricted users/agents, scopes,
personal isolation, token revocation, human handoffs, callback replay,
execution approvals, authorized self-targeted policy changes,
self-approval denial, and current authority before commit. Reproduce API
checks with `pnpm exec vitest run
server/src/__tests__/connection-management.integration.test.ts
server/src/__tests__/openapi-routes.test.ts`, using a fresh database
through `PAPERCLIP_CONNECTION_MANAGEMENT_TEST_DATABASE_URL` or the
default embedded test database.
- Companion #17739 also records consent separately from token refresh so
saved Google choices survive refresh. Its eight service-picker and two
local-HTTP OAuth tests pass; both new UI cases were red before the fix.
Normal migration generation confirms no SQL change is needed for the
additive JSON metadata.
- The integration module shares one assembled server, authentication
factory, and provider lifecycle to preserve the
HTTP-to-vault-to-task-continuation proof. A reused external database
caused a Slack fixture identity conflict; the fresh final run passed.
Earlier fixture/transport and contract-update failures remain in the
companion qualification record.
- The broad local `pnpm test:run` attempt remains blocked by macOS
embedded PostgreSQL's host semaphore limit. It is not a clean pass. The
fresh Linux CI matrix must complete. Provider fixtures do not prove live
setup or an empirical LLM success rate.
- A current-head completed Paperclip assessment is not yet recorded. Its
earlier external recovery boundary has not been bypassed, and no
incomplete assessment is reported as passing. The user authorized both
merges when checks pass; merge this implementation first, then replay,
retarget, and requalify companion #17739 against the squash-merged
master.
- After the master refresh, local workspace typecheck/build, **97
actual-auth/OpenAPI cases** and **141 gateway/policy cases** pass. The
original fixed database port was occupied; Docker assigned a free
localhost port. The first neighbor setup command could not resolve root
`tsx`, leaving its schema uninitialized; the built database package
migrated the separate fixture and all unchanged cases passed. Both setup
failures are retained in qualification. Fresh Linux CI remains required;
no full local test-sweep pass is claimed.
- The f9 Greptile review scored **2/5** for two reproduced findings:
Slack test sends skipped the caller’s tool policy, and healthy App
credentials completed an unconfirmed identity handoff. Both are fixed in
this head and have resolved evidence threads
([Slack](https://github.com/paperclipai/paperclip/pull/17737#discussion_r4384927765),
[identity](https://github.com/paperclipai/paperclip/pull/17737#discussion_r4384927895)).
Actual key/JWT cases cover twelve Slack caller/target/recipient
combinations; the human-session GitHub OAuth callback alone remains
pending until explicit confirmation. All **99 API/OpenAPI tests** (72
actual-auth + 27 contracts), workspace typecheck and build pass. On the
combined companion, all four focused cases (including the twelve Slack
combinations), typecheck/build and maps also pass. The continuation
suite’s 50 embedded-PG cases were skipped because its database could not
start locally; fresh Linux CI must run them. Initial fixture
credential-collision and audit-projection assertion failures are
retained with the red reproductions in the companion qualification
record. No full local sweep or live consent is claimed.
## Risks
- The maintainer explicitly confirmed authorized policy administration,
including self-targeted changes that loosen controls. These writes
require management grants and the responsible user’s current authority.
Agents cannot approve their own governed action requests or edit their
own principal permission grants. The actual-auth regression exercises
both permitted administration and those denials.
- This is a broad authorization change. Incorrect scope or owner
resolution could deny permitted setup or expose another user's
resources. Integration cases cover both permitted and denied requests
with actual authentication.
- The additive nullable gateway-token column does not infer identities
for legacy clients or backfill agent grants. Legacy agent tokens without
a responsible user fail closed.
- Provider fixtures test supported setup and callback contracts. They do
not prove live provider availability.
## Model Used
- OpenAI Codex, GPT-6 family, with reasoning, repository tools, and code
execution. The runtime does not expose a more specific deployment ID or
context-window size.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass — focused suites above;
full local sweep remains blocked as documented
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green — exact `2ecd6451d0` Linux CI
completed SUCCESS; external Paperclip Review is still queued
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
exact `2ecd6451d0` review completed; both f9 findings have resolved
evidence replies
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
310 lines
13 KiB
TypeScript
310 lines
13 KiB
TypeScript
import { isProvisionedSlackSetup } from "@paperclipai/shared";
|
|
import type { EndpointRow, DbOrTransaction, SlackCallbackSurface, InternalSetupState } from "../runtime-types.js";
|
|
|
|
import { notifyChatVerificationWork } from "../../chat-work-notifications.js";
|
|
|
|
import { slackChatRegistrationService } from "../../chat-slack-registration.js";
|
|
import { chatSlackRegistrations } from "@paperclipai/db";
|
|
|
|
import { runtimeCanonicalOrigin } from "../../cloud-runtime-identity.js";
|
|
|
|
import {
|
|
createHash,
|
|
createHmac,
|
|
timingSafeEqual,
|
|
} from "node:crypto";
|
|
import {
|
|
and,
|
|
eq,
|
|
} from "drizzle-orm";
|
|
|
|
import type { Db } from "@paperclipai/db";
|
|
|
|
import {
|
|
chatEndpoints,
|
|
toolConnections,
|
|
} from "@paperclipai/db";
|
|
import type {
|
|
ToolCredentialSecretRef,
|
|
} from "@paperclipai/shared";
|
|
|
|
import {
|
|
logActivity,
|
|
} from "../../activity-log.js";
|
|
|
|
import { secretService } from "../../secrets.js";
|
|
|
|
/** A signed provider challenge remains valid when those exact credentials enter the runtime vault. */
|
|
export function preservesProvisionedSlackVerification(setup: EndpointRow["setup"], signingSecret: string, webhookUrl: string): boolean {
|
|
const internal = setup as InternalSetupState;
|
|
const observedUrl = internal.slackCallbackSurfaces?.events?.url;
|
|
return !!setup.webhookVerifiedAt && isProvisionedSlackSetup(setup.slackSetupMethod)
|
|
&& internal.slackVerificationSigningFingerprint === createHash("sha256").update(signingSecret).digest("hex")
|
|
&& !!observedUrl && slackCallbackMatchesPublicUrl(observedUrl, webhookUrl);
|
|
}
|
|
|
|
function slackRequestSignatureIsValid(
|
|
request: Request,
|
|
body: string,
|
|
signingSecret: string,
|
|
): boolean {
|
|
const timestamp = request.headers.get("x-slack-request-timestamp");
|
|
const signature = request.headers.get("x-slack-signature");
|
|
if (!timestamp || !signature) return false;
|
|
const timestampSeconds = Number(timestamp);
|
|
if (
|
|
!Number.isFinite(timestampSeconds) ||
|
|
Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > 300
|
|
)
|
|
return false;
|
|
const expected = `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`;
|
|
try {
|
|
return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function slackRequestWorkspaceId(
|
|
body: string,
|
|
contentType: string,
|
|
): string | null {
|
|
let payload: unknown;
|
|
try {
|
|
if (contentType.includes("application/json")) {
|
|
payload = JSON.parse(body);
|
|
} else {
|
|
const form = new URLSearchParams(body);
|
|
const interactivePayload = form.get("payload");
|
|
payload = interactivePayload
|
|
? JSON.parse(interactivePayload)
|
|
: Object.fromEntries(form.entries());
|
|
}
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!payload || typeof payload !== "object") return null;
|
|
const record = payload as Record<string, unknown>;
|
|
const nestedId = (value: unknown): string | null => {
|
|
if (!value || typeof value !== "object") return null;
|
|
const id = (value as Record<string, unknown>).id;
|
|
return typeof id === "string" && id.length > 0 ? id : null;
|
|
};
|
|
const stringField = (key: string): string | null => {
|
|
const value = record[key];
|
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
};
|
|
const authorization = Array.isArray(record.authorizations)
|
|
? record.authorizations.find(
|
|
(value): value is Record<string, unknown> =>
|
|
Boolean(value) && typeof value === "object",
|
|
)
|
|
: null;
|
|
const authorizationField = (key: string): string | null => {
|
|
const value = authorization?.[key];
|
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
};
|
|
|
|
// A Grid event may carry both an enterprise id and the concrete workspace
|
|
// id. The bot identity is verified against auth.test's team_id, so prefer a
|
|
// team id and use the enterprise id only when Slack omitted team context.
|
|
return (
|
|
stringField("team_id") ??
|
|
nestedId(record.team) ??
|
|
authorizationField("team_id") ??
|
|
stringField("enterprise_id") ??
|
|
nestedId(record.enterprise) ??
|
|
authorizationField("enterprise_id")
|
|
);
|
|
}
|
|
|
|
function canonicalCallbackUrl(value: string): string | null {
|
|
try {
|
|
const url = new URL(value);
|
|
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
|
url.hostname = url.hostname.replace(/\.$/, "");
|
|
url.username = "";
|
|
url.password = "";
|
|
url.search = "";
|
|
url.hash = "";
|
|
return url.toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// TLS terminates at a reverse proxy in many self-hosted deployments. The
|
|
// transport scheme is not evidence of URL drift; authority and path still are.
|
|
// This is diagnostic only: it does not trust forwarded headers or change auth.
|
|
function slackCallbackMatchesPublicUrl(observed: string, current: string): boolean {
|
|
const canonical = canonicalCallbackUrl(observed);
|
|
if (canonical === current) return true;
|
|
if (!canonical) return false;
|
|
const observedUrl = new URL(canonical);
|
|
const currentUrl = new URL(current);
|
|
return observedUrl.protocol === "http:"
|
|
&& currentUrl.protocol === "https:"
|
|
&& observedUrl.host === currentUrl.host
|
|
&& observedUrl.pathname === currentUrl.pathname;
|
|
}
|
|
|
|
async function inspectSlackCallback(
|
|
request: Request,
|
|
): Promise<SlackCallbackInspection | null> {
|
|
const url = slackCallbackObservationUrl(request);
|
|
if (!url) return null;
|
|
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
let body: string;
|
|
try {
|
|
body = await request.text();
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (contentType.includes("application/json")) {
|
|
try {
|
|
const payload = JSON.parse(body) as {
|
|
type?: unknown;
|
|
challenge?: unknown;
|
|
};
|
|
const isUrlVerification =
|
|
payload.type === "url_verification" &&
|
|
typeof payload.challenge === "string" &&
|
|
payload.challenge.length > 0;
|
|
if (isUrlVerification || payload.type === "event_callback") {
|
|
return {
|
|
surface: "events",
|
|
url,
|
|
isUrlVerification,
|
|
};
|
|
}
|
|
} catch {
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const form = new URLSearchParams(body);
|
|
if (form.get("command")) {
|
|
return { surface: "slashCommands", url, isUrlVerification: false };
|
|
}
|
|
const interactivePayload = form.get("payload");
|
|
if (!interactivePayload) return null;
|
|
try {
|
|
const payload = JSON.parse(interactivePayload) as { type?: unknown };
|
|
if (
|
|
typeof payload.type === "string" &&
|
|
[
|
|
"block_actions",
|
|
"block_suggestion",
|
|
"dialog_submission",
|
|
"message_action",
|
|
"shortcut",
|
|
"view_closed",
|
|
"view_submission",
|
|
"workflow_step_edit",
|
|
].includes(payload.type)
|
|
) {
|
|
return { surface: "interactivity", url, isUrlVerification: false };
|
|
}
|
|
} catch {
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
type SlackCallbackInspection = {
|
|
surface: SlackCallbackSurface;
|
|
url: string;
|
|
isUrlVerification: boolean;
|
|
};
|
|
|
|
// Cloud records the public request host in dedicated headers so provider edges
|
|
// cannot replace it with their upstream host. Only use callback-health evidence on a
|
|
// claimed Cloud instance, after provider authentication succeeded. It must not
|
|
// change the Request passed to the adapter, signature verification, routing,
|
|
// board identity, or the configured URL used to generate callbacks.
|
|
function slackCallbackObservationUrl(request: Request): string | null {
|
|
const directUrl = canonicalCallbackUrl(request.url);
|
|
if (!directUrl || !runtimeCanonicalOrigin()) return directUrl;
|
|
const hasCloudEvidence = request.headers.has("x-paperclip-cloud-forwarded-host");
|
|
const host = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-host" : "x-forwarded-host")?.trim();
|
|
const protocol = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-proto" : "x-forwarded-proto")?.trim();
|
|
if (!host || /[\s/@\\?#,]/.test(host) || (protocol !== "https" && protocol !== "http")) return directUrl;
|
|
try {
|
|
const origin = new URL(`${protocol}://${host}`);
|
|
// Accept one authority only, never credentials, paths, queries, or lists.
|
|
if (!origin.host || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) return directUrl;
|
|
const observed = new URL(directUrl);
|
|
observed.protocol = origin.protocol;
|
|
observed.host = origin.host;
|
|
observed.port = origin.port;
|
|
return canonicalCallbackUrl(observed.toString());
|
|
} catch {
|
|
return directUrl;
|
|
}
|
|
}
|
|
export { slackRequestSignatureIsValid, slackRequestWorkspaceId, canonicalCallbackUrl, slackCallbackMatchesPublicUrl, inspectSlackCallback };
|
|
|
|
type SlackCallbackVerificationOptions = {
|
|
resolveCredentialRefs: (endpoint: EndpointRow, refs: ToolCredentialSecretRef[], database?: DbOrTransaction) => Promise<Record<string, string>>;
|
|
getWebhookPublicBaseUrl: () => string | null;
|
|
scheduleMessageProcessing: (task: () => Promise<void>) => void;
|
|
slackRegistration: Pick<ReturnType<typeof slackChatRegistrationService>, "notifyVerified">;
|
|
};
|
|
|
|
export function createSlackCallbackVerification(db: Db, options: SlackCallbackVerificationOptions) {
|
|
const { resolveCredentialRefs, getWebhookPublicBaseUrl, scheduleMessageProcessing, slackRegistration } = options;
|
|
|
|
|
|
async function verifySlackRequestUrl(endpoint: EndpointRow, request: Request): Promise<Response | null> {
|
|
const callback = await inspectSlackCallback(request.clone());
|
|
if (!callback?.isUrlVerification) return null;
|
|
const body = await request.clone().text();
|
|
let notifyAccount = false;
|
|
// URL verification needs only the signing secret. Do not initialize the
|
|
// SDK (which calls Slack auth.test), wait for OAuth, or acquire the creation
|
|
// lease: Slack can deliver this check while app setup still owns that lease.
|
|
const response = await db.transaction(async tx => {
|
|
const [current] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)).for("no key update");
|
|
if (!current || ["archived", "paused", "revoked"].includes(current.status)) return new Response("ignored", { status: 200 });
|
|
const [connection] = await tx.select({ status: toolConnections.status, refs: toolConnections.credentialSecretRefs }).from(toolConnections)
|
|
.where(and(eq(toolConnections.id, current.connectionId), eq(toolConnections.companyId, current.companyId)));
|
|
if (!connection || connection.status === "archived") return new Response("ignored", { status: 200 });
|
|
let secret = (await resolveCredentialRefs(current, connection.refs.filter(ref => ref.configPath.replace(/^credentials\./, "") === "signingSecret"), tx)).signingSecret;
|
|
if (!secret && isProvisionedSlackSetup(current.setup.slackSetupMethod)) {
|
|
const [registration] = await tx.select().from(chatSlackRegistrations)
|
|
.where(and(eq(chatSlackRegistrations.endpointId, current.id), eq(chatSlackRegistrations.companyId, current.companyId)));
|
|
if (registration?.status !== "removed" && registration?.secretIds.signingSecret) {
|
|
secret = await secretService(tx as unknown as Db).resolveSecretValue(current.companyId, registration.secretIds.signingSecret, "latest", {
|
|
accessContext: { consumerType: "system", consumerId: `slack-registration:${current.id}`, configPath: "slack_registration.signingSecret", actorType: "system" },
|
|
});
|
|
}
|
|
}
|
|
if (!secret) return new Response("Slack signing secret is not ready yet", { status: 503 });
|
|
if (!slackRequestSignatureIsValid(request, body, secret)) return new Response("Invalid signature", { status: 401 });
|
|
const workspaceId = slackRequestWorkspaceId(body, request.headers.get("content-type") ?? "");
|
|
if (workspaceId && current.providerAccountId && workspaceId !== current.providerAccountId) return new Response("ignored", { status: 200 });
|
|
const observedAt = new Date();
|
|
const setup = current.setup as InternalSetupState;
|
|
const matchesCurrentUrl = slackCallbackMatchesPublicUrl(callback.url, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${current.publicId}/slack`);
|
|
await notifyChatVerificationWork(tx);
|
|
await tx.update(chatEndpoints).set({ setup: {
|
|
...setup,
|
|
...(matchesCurrentUrl ? { webhookVerifiedAt: setup.webhookVerifiedAt ?? observedAt.toISOString(),
|
|
slackVerificationSigningFingerprint: createHash("sha256").update(secret).digest("hex") } : {}),
|
|
slackCallbackSurfaces: { ...setup.slackCallbackSurfaces, events: { url: callback.url, observedAt: observedAt.toISOString() } },
|
|
...(matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus
|
|
? { slackAccount: { ...setup.slackAccount, verificationStatus: "pending" as const } } : {}),
|
|
} as InternalSetupState, ...(matchesCurrentUrl ? { healthMessage: "Slack Events Request URL verified" } : {}), updatedAt: observedAt }).where(eq(chatEndpoints.id, current.id));
|
|
if (matchesCurrentUrl && !setup.webhookVerifiedAt) await logActivity(tx as unknown as Db, { companyId: current.companyId, actorType: "system", actorId: "slack-webhook",
|
|
action: "chat_endpoint.webhook_verified", entityType: "tool_connection", entityId: current.connectionId,
|
|
details: { endpointId: current.id, provider: "slack" } });
|
|
notifyAccount = matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus;
|
|
return Response.json({ challenge: (JSON.parse(body) as { challenge: string }).challenge });
|
|
});
|
|
if (notifyAccount) scheduleMessageProcessing(() => slackRegistration.notifyVerified(endpoint.id));
|
|
return response;
|
|
}
|
|
return { verifySlackRequestUrl };
|
|
}
|