@pithy-sh/auth 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +58 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +59 -1
- package/dist/audit/emit.d.ts +36 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +48 -2
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +47 -8
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +56 -6
- package/dist/client/api.d.ts +55 -12
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +57 -18
- package/dist/client/bearer.d.ts +110 -0
- package/dist/client/bearer.d.ts.map +1 -0
- package/dist/client/bearer.js +265 -0
- package/dist/client/handoff.d.ts +77 -0
- package/dist/client/handoff.d.ts.map +1 -0
- package/dist/client/handoff.js +119 -0
- package/dist/client/mcp.d.ts +70 -0
- package/dist/client/mcp.d.ts.map +1 -0
- package/dist/client/mcp.js +65 -0
- package/dist/data/betterAuth.d.ts +3 -2
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +5 -3
- package/dist/data/kitFields.d.ts +5 -0
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +5 -0
- package/dist/data/tables.d.ts +26 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +10 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +8 -3
- package/dist/data/verificationOutcome.d.ts +53 -0
- package/dist/data/verificationOutcome.d.ts.map +1 -0
- package/dist/data/verificationOutcome.js +50 -0
- package/dist/email/send.js +6 -2
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +319 -8
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -10
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +76 -10
- package/dist/http/handoff.d.ts +76 -0
- package/dist/http/handoff.d.ts.map +1 -0
- package/dist/http/handoff.js +316 -0
- package/dist/http/middleware.d.ts +37 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +68 -6
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +322 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +202 -5
- package/dist/http/routes.d.ts +3 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +78 -5
- package/dist/http/schemas.d.ts +114 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +94 -1
- package/dist/http/views.d.ts +60 -3
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +143 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/instance/auth.d.ts +148 -10
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +87 -42
- package/dist/instance/plugins.d.ts +6 -0
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +14 -1
- package/dist/ledger/read.d.ts +53 -0
- package/dist/ledger/read.d.ts.map +1 -0
- package/dist/ledger/read.js +85 -0
- package/dist/ledger/record.d.ts +35 -0
- package/dist/ledger/record.d.ts.map +1 -0
- package/dist/ledger/record.js +98 -0
- package/dist/lifecycle/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +37 -2
- package/dist/lifecycle/enforce.d.ts.map +1 -1
- package/dist/lifecycle/enforce.js +46 -5
- package/dist/lifecycle/erasure.d.ts +9 -0
- package/dist/lifecycle/erasure.d.ts.map +1 -0
- package/dist/lifecycle/erasure.js +96 -0
- package/dist/lifecycle/inactivity.d.ts +19 -0
- package/dist/lifecycle/inactivity.d.ts.map +1 -0
- package/dist/lifecycle/inactivity.js +28 -0
- package/dist/lifecycle/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +5 -2
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +6 -2
- package/dist/lifecycle/transitions.d.ts +179 -18
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +391 -70
- package/dist/mcp/argumentClass.d.ts +51 -0
- package/dist/mcp/argumentClass.d.ts.map +1 -0
- package/dist/mcp/argumentClass.js +69 -0
- package/dist/mcp/capability.d.ts +50 -0
- package/dist/mcp/capability.d.ts.map +1 -0
- package/dist/mcp/capability.js +140 -0
- package/dist/mcp/clientMetadata.d.ts +40 -0
- package/dist/mcp/clientMetadata.d.ts.map +1 -0
- package/dist/mcp/clientMetadata.js +68 -0
- package/dist/mcp/consent.d.ts +49 -0
- package/dist/mcp/consent.d.ts.map +1 -0
- package/dist/mcp/consent.js +69 -0
- package/dist/mcp/dispatch.d.ts +35 -0
- package/dist/mcp/dispatch.d.ts.map +1 -0
- package/dist/mcp/dispatch.js +135 -0
- package/dist/mcp/floor.d.ts +37 -0
- package/dist/mcp/floor.d.ts.map +1 -0
- package/dist/mcp/floor.js +41 -0
- package/dist/mcp/host.d.ts +34 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +2 -0
- package/dist/mcp/http/redirectList.d.ts +9 -0
- package/dist/mcp/http/redirectList.d.ts.map +1 -0
- package/dist/mcp/http/redirectList.js +24 -0
- package/dist/mcp/http/responses.d.ts +143 -0
- package/dist/mcp/http/responses.d.ts.map +1 -0
- package/dist/mcp/http/responses.js +83 -0
- package/dist/mcp/http/routes.d.ts +28 -0
- package/dist/mcp/http/routes.d.ts.map +1 -0
- package/dist/mcp/http/routes.js +517 -0
- package/dist/mcp/http/schemas.d.ts +24 -0
- package/dist/mcp/http/schemas.d.ts.map +1 -0
- package/dist/mcp/http/schemas.js +18 -0
- package/dist/mcp/marker.d.ts +15 -0
- package/dist/mcp/marker.d.ts.map +1 -0
- package/dist/mcp/marker.js +15 -0
- package/dist/mcp/provider.d.ts +78 -0
- package/dist/mcp/provider.d.ts.map +1 -0
- package/dist/mcp/provider.js +108 -0
- package/dist/mcp/purge.d.ts +15 -0
- package/dist/mcp/purge.d.ts.map +1 -0
- package/dist/mcp/purge.js +31 -0
- package/dist/mcp/rpc.d.ts +79 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +103 -0
- package/dist/mcp/toolAudit.d.ts +76 -0
- package/dist/mcp/toolAudit.d.ts.map +1 -0
- package/dist/mcp/toolAudit.js +86 -0
- package/dist/migrations/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -0
- package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
- package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
- package/dist/migrations/0006_verification_outcomes.js +35 -0
- package/dist/migrations/0007_erasure_record.d.ts +17 -0
- package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
- package/dist/migrations/0007_erasure_record.js +36 -0
- package/dist/migrations/0008_last_active.d.ts +15 -0
- package/dist/migrations/0008_last_active.d.ts.map +1 -0
- package/dist/migrations/0008_last_active.js +29 -0
- package/dist/migrations/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +5 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +10 -2
- package/dist/peer.d.ts +3 -2
- package/dist/peer.d.ts.map +1 -1
- package/dist/processing/activities.d.ts +6 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +12 -0
- package/dist/purge/contribution.d.ts +62 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +155 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +158 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +205 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +71 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +140 -0
- package/dist/test-utils/accountFootprint.d.ts +13 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +49 -0
- package/dist/test-utils/liveApp.d.ts +6 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +7 -2
- package/dist/token/handoff.d.ts +80 -0
- package/dist/token/handoff.d.ts.map +1 -0
- package/dist/token/handoff.js +136 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +176 -12
- package/docs/apple-signin.md +32 -4
- package/docs/facebook-oauth.md +2 -2
- package/docs/github-oauth.md +2 -2
- package/docs/google-oauth.md +9 -7
- package/docs/microsoft-oauth.md +2 -2
- package/package.json +11 -5
- package/pithy.manifest.json +2 -2
- package/pithy.mcp.manifest.json +36 -0
- package/src/audit/actions.ts +58 -0
- package/src/audit/emit.ts +66 -1
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +122 -18
- package/src/client/api.ts +69 -19
- package/src/client/bearer.ts +388 -0
- package/src/client/handoff.ts +172 -0
- package/src/client/mcp.ts +140 -0
- package/src/data/betterAuth.ts +8 -4
- package/src/data/kitFields.ts +2 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +19 -4
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +465 -4
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +79 -10
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +74 -5
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +374 -3
- package/src/http/routes.ts +116 -5
- package/src/http/schemas.ts +195 -0
- package/src/http/views.ts +192 -3
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +58 -3
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +55 -5
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +10 -2
- package/src/lifecycle/transitions.ts +552 -93
- package/src/mcp/argumentClass.ts +112 -0
- package/src/mcp/capability.ts +194 -0
- package/src/mcp/clientMetadata.ts +81 -0
- package/src/mcp/consent.ts +95 -0
- package/src/mcp/dispatch.ts +154 -0
- package/src/mcp/floor.ts +62 -0
- package/src/mcp/host.ts +36 -0
- package/src/mcp/http/redirectList.ts +26 -0
- package/src/mcp/http/responses.ts +157 -0
- package/src/mcp/http/routes.ts +635 -0
- package/src/mcp/http/schemas.ts +37 -0
- package/src/mcp/marker.ts +18 -0
- package/src/mcp/provider.ts +151 -0
- package/src/mcp/purge.ts +39 -0
- package/src/mcp/rpc.ts +135 -0
- package/src/mcp/toolAudit.ts +132 -0
- package/src/migrations/0005_purge_once.ts +42 -0
- package/src/migrations/0006_verification_outcomes.ts +51 -0
- package/src/migrations/0007_erasure_record.ts +43 -0
- package/src/migrations/0008_last_active.ts +30 -0
- package/src/migrations/pluginTables.ts +19 -1
- package/src/migrations/set.ts +9 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +218 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +348 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +202 -0
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +104 -0
- package/src/test-utils/liveApp.ts +10 -1
- package/src/token/handoff.ts +180 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type ClientDiscovery, oauthProvider } from "@better-auth/oauth-provider";
|
|
5
|
+
import type { BetterAuthPlugin } from "better-auth";
|
|
6
|
+
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The authorization server the MCP capability composes into the auth instance (`docs/AGENT-ACCESS.md` §4).
|
|
10
|
+
*
|
|
11
|
+
* **Composed, not written.** Better Auth's OAuth 2.1 provider turns the instance into an authorization server:
|
|
12
|
+
* dynamic client registration, PKCE, resource-bound JWT access tokens signed by the JWKS the `jwt` plugin already
|
|
13
|
+
* keeps, refresh tokens, and the RFC 8414 metadata a client discovers it by. Beside registration, this module plugs in
|
|
14
|
+
* the Client ID Metadata Document discovery from `@better-auth/cimd` (`./clientMetadata.ts`), so a client may also be
|
|
15
|
+
* known by the URL of a document it publishes. That one extension adds the registration path the MCP specification
|
|
16
|
+
* prefers; everything else this module adds is policy, and every line of that narrows the provider's defaults.
|
|
17
|
+
*
|
|
18
|
+
* **One scope, and it is not a permission.** The consent is informational (§4.3): one decision, *let this client
|
|
19
|
+
* act as you in this application*, so the token carries no permission selection. {@link MCP_SCOPE} is the only
|
|
20
|
+
* scope a client may hold beside `offline_access`, which buys a refresh token and nothing else. The role is the only
|
|
21
|
+
* authority over what a call may do, and the routes enforce it, so there is no scope vocabulary to ask for.
|
|
22
|
+
*
|
|
23
|
+
* **The token binds the resource and the user, and nothing else.** The one resource is this Worker's MCP endpoint,
|
|
24
|
+
* seeded as the provider's only resource and linked to every client at registration, so a token minted for it is a
|
|
25
|
+
* JWT whose `aud` is that URL and cannot be replayed at another. `sub` is the user and `sid` the session they
|
|
26
|
+
* consented in; the MCP endpoint refuses a token whose session has ended.
|
|
27
|
+
*
|
|
28
|
+
* **No client credentials grant.** A token here acts *as somebody*; a machine-to-machine token acts as nobody, which
|
|
29
|
+
* is the control-plane seam's job (§1), not this one's.
|
|
30
|
+
*
|
|
31
|
+
* **The consent screen every time.** The provider skips consent for a client that already holds it; this kit asks
|
|
32
|
+
* again, so a client asking for access again is a new decision the user can see, and an audited one. A client asking
|
|
33
|
+
* to be shown nothing (`prompt=none`) is refused with `consent_required` before the provider runs, because the
|
|
34
|
+
* provider would answer it with a code whenever a consent is on record.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/** The one OAuth scope this server issues. A constant, not a vocabulary. */
|
|
38
|
+
export const MCP_SCOPE = "mcp";
|
|
39
|
+
|
|
40
|
+
/** The scopes a client may request: {@link MCP_SCOPE}, and `offline_access` for a refresh token. */
|
|
41
|
+
export const MCP_SCOPES = [MCP_SCOPE, "offline_access"] as const;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The provider's tables, under this capability's prefix. Better Auth names a plugin's tables after its models;
|
|
45
|
+
* every table this kit provides is `pithy_<capability>_<table>`, so each one is renamed here, once.
|
|
46
|
+
*/
|
|
47
|
+
export const MCP_MODEL_NAMES = {
|
|
48
|
+
oauthClient: "pithyMcpClients",
|
|
49
|
+
oauthResource: "pithyMcpResources",
|
|
50
|
+
oauthClientResource: "pithyMcpClientResources",
|
|
51
|
+
oauthRefreshToken: "pithyMcpRefreshTokens",
|
|
52
|
+
oauthAccessToken: "pithyMcpAccessTokens",
|
|
53
|
+
oauthConsent: "pithyMcpConsents",
|
|
54
|
+
oauthClientAssertion: "pithyMcpClientAssertions",
|
|
55
|
+
} as const;
|
|
56
|
+
|
|
57
|
+
/** The plugin id of the kit's consent-every-time hook. */
|
|
58
|
+
export const MCP_CONSENT_PLUGIN_ID = "pithy-mcp-consent";
|
|
59
|
+
|
|
60
|
+
/** What the provider needs to know about this Worker. */
|
|
61
|
+
export interface McpProviderSettings {
|
|
62
|
+
/** The MCP endpoint's absolute URL: the one resource, and every token's audience. */
|
|
63
|
+
readonly resource: string;
|
|
64
|
+
/** The scaffolded screen's path, which is both the sign-in and the consent page for this flow. */
|
|
65
|
+
readonly consentPage: string;
|
|
66
|
+
/** How a client whose id is an HTTPS URL is resolved from the metadata document served there. */
|
|
67
|
+
readonly clientDiscovery: ClientDiscovery;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The `prompt` an authorize request runs with — always including `consent` — or `null` when the client asked for
|
|
72
|
+
* `none`. `none` asks for a grant with no screen, and this server has no such grant to give.
|
|
73
|
+
*/
|
|
74
|
+
export function consentPrompt(prompt: unknown): string | null {
|
|
75
|
+
const asked = typeof prompt === "string" ? prompt.split(" ").filter((value) => value.length > 0) : [];
|
|
76
|
+
if (asked.includes("none")) return null;
|
|
77
|
+
return [...new Set([...asked.filter((value) => value !== "login"), "consent"])].join(" ");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Show the consent screen on every authorization, so asking again is a decision rather than a skip. */
|
|
81
|
+
function consentEveryTime(): BetterAuthPlugin {
|
|
82
|
+
return {
|
|
83
|
+
id: MCP_CONSENT_PLUGIN_ID,
|
|
84
|
+
hooks: {
|
|
85
|
+
before: [
|
|
86
|
+
{
|
|
87
|
+
// The browser's own authorize request, and only that. The provider calls its authorize endpoint again
|
|
88
|
+
// from inside the consent endpoint once the user has decided, with `consent` already taken out of the
|
|
89
|
+
// prompt — and that call carries the consent request, so it is told apart by the path the request was
|
|
90
|
+
// actually made to. Matching it too would send the user straight back to the screen they just answered.
|
|
91
|
+
matcher: (context) =>
|
|
92
|
+
context.path === "/oauth2/authorize" &&
|
|
93
|
+
context.request !== undefined &&
|
|
94
|
+
new URL(context.request.url).pathname.endsWith("/oauth2/authorize"),
|
|
95
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
96
|
+
const query = (ctx.query ?? {}) as Record<string, unknown>;
|
|
97
|
+
const prompt = consentPrompt(query.prompt);
|
|
98
|
+
if (prompt === null) {
|
|
99
|
+
// Answered here rather than at the redirect URI: the request has not been checked against the client
|
|
100
|
+
// yet, so its redirect URI is only what the request says.
|
|
101
|
+
throw new APIError("BAD_REQUEST", {
|
|
102
|
+
error: "consent_required",
|
|
103
|
+
error_description: "This application asks for consent every time, so prompt=none is never granted.",
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return { context: { query: { ...query, prompt } } };
|
|
107
|
+
}),
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The provider plugin and the kit's consent hook, for one Worker's MCP endpoint.
|
|
116
|
+
*
|
|
117
|
+
* Typed as plain `BetterAuthPlugin`s, the way the kit's translator and sign-in gate are. Every reader takes them as
|
|
118
|
+
* that already: the instance's plugin list is the adopter's `BetterAuthPlugin[]` with these appended, and the
|
|
119
|
+
* migration plan reads a `BetterAuthPlugin[]`. So the widening erases nothing a caller sees, and it keeps the
|
|
120
|
+
* provider's inferred type out of the shipped declaration, which would otherwise name `better-call` internals a
|
|
121
|
+
* declaration cannot reach.
|
|
122
|
+
*/
|
|
123
|
+
export function mcpAuthorizationServer(settings: McpProviderSettings): McpProviderPlugins {
|
|
124
|
+
return [
|
|
125
|
+
oauthProvider({
|
|
126
|
+
loginPage: settings.consentPage,
|
|
127
|
+
consentPage: settings.consentPage,
|
|
128
|
+
scopes: [...MCP_SCOPES],
|
|
129
|
+
grantTypes: ["authorization_code", "refresh_token"],
|
|
130
|
+
// Open registration is what lets a client reach an authorized session from a URL alone (§4.3), which is why
|
|
131
|
+
// nothing a client says about itself at registration is presented as verified on the consent screen.
|
|
132
|
+
allowDynamicClientRegistration: true,
|
|
133
|
+
allowUnauthenticatedClientRegistration: true,
|
|
134
|
+
// A native MCP client registers an `http://127.0.0.1` callback and often omits `application_type`; inferring
|
|
135
|
+
// it admits those without loosening the rules for a web client's redirect.
|
|
136
|
+
clientRegistrationDefaultApplicationType: "infer",
|
|
137
|
+
// A client whose id is its metadata document's URL needs no registration; any other client registers
|
|
138
|
+
// dynamically.
|
|
139
|
+
extensions: [{ clientDiscovery: settings.clientDiscovery }],
|
|
140
|
+
resources: [settings.resource],
|
|
141
|
+
clientRegistrationDefaultResources: [settings.resource],
|
|
142
|
+
schema: Object.fromEntries(
|
|
143
|
+
Object.entries(MCP_MODEL_NAMES).map(([model, modelName]) => [model, { modelName }]),
|
|
144
|
+
) as never,
|
|
145
|
+
}),
|
|
146
|
+
consentEveryTime(),
|
|
147
|
+
];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The plugins {@link mcpAuthorizationServer} composes: the provider, then the consent hook. */
|
|
151
|
+
export type McpProviderPlugins = readonly [provider: BetterAuthPlugin, consent: BetterAuthPlugin];
|
package/src/mcp/purge.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { PurgeContext } from "@pithy-sh/core/src/capability/purge";
|
|
5
|
+
import { authDatabase } from "../data/tables";
|
|
6
|
+
import { bindingOf, pluginRows, prepared, untyped } from "../purge/contribution";
|
|
7
|
+
import { MCP_MODEL_NAMES } from "./provider";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* What erasing and exporting a person means for the provider's tables.
|
|
11
|
+
*
|
|
12
|
+
* The rows keyed to a person are the consents they gave and the tokens minted under them. A dynamically registered
|
|
13
|
+
* client is not theirs — it is the application's record of itself, written before anybody signed in — so it stays.
|
|
14
|
+
*/
|
|
15
|
+
export const MCP_USER_TABLES = [
|
|
16
|
+
MCP_MODEL_NAMES.oauthConsent,
|
|
17
|
+
MCP_MODEL_NAMES.oauthAccessToken,
|
|
18
|
+
MCP_MODEL_NAMES.oauthRefreshToken,
|
|
19
|
+
] as const;
|
|
20
|
+
|
|
21
|
+
/** Erase one person's consents and tokens. Succeeds, having found nothing, when they are already gone. */
|
|
22
|
+
export async function eraseMcpUser(context: PurgeContext, database: string): Promise<void> {
|
|
23
|
+
const d1 = bindingOf(context.env, database);
|
|
24
|
+
const db = untyped(authDatabase(d1));
|
|
25
|
+
await d1.batch(
|
|
26
|
+
MCP_USER_TABLES.map((table) =>
|
|
27
|
+
prepared(d1, db.deleteFrom(table).where("userId", "=", context.subject.id).compile()),
|
|
28
|
+
),
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One person's consents and tokens, every column but a credential's. */
|
|
33
|
+
export async function exportMcpUser(context: PurgeContext, database: string): Promise<Record<string, unknown>> {
|
|
34
|
+
const db = authDatabase(bindingOf(context.env, database));
|
|
35
|
+
const tables = await Promise.all(
|
|
36
|
+
MCP_USER_TABLES.map(async (table) => [table, await pluginRows(db, table, context.subject.id)] as const),
|
|
37
|
+
);
|
|
38
|
+
return Object.fromEntries(tables);
|
|
39
|
+
}
|
package/src/mcp/rpc.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { AppTool } from "@pithy-sh/core/src/mcp/tools";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The MCP protocol the endpoint speaks: streamable HTTP, stateless, JSON responses.
|
|
9
|
+
*
|
|
10
|
+
* **Four methods and one notification**, because that is the whole of a tools-only server: `initialize`, `ping`,
|
|
11
|
+
* `tools/list`, `tools/call`, and `notifications/initialized`. Each POST carries one JSON-RPC message and is
|
|
12
|
+
* answered in the response body, so there is no session to keep, no stream to hold open, and nothing an isolate
|
|
13
|
+
* has to remember between requests — the caller is re-verified on every one. A notification is answered `202`
|
|
14
|
+
* with no body.
|
|
15
|
+
*
|
|
16
|
+
* **Pure.** The handlers are handed in; this module decides what a message means and what its answer looks like,
|
|
17
|
+
* and nothing about who is asking.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** The protocol versions this server speaks, newest first. */
|
|
21
|
+
export const MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"] as const;
|
|
22
|
+
|
|
23
|
+
/** One JSON-RPC 2.0 message, as a client sends it. */
|
|
24
|
+
export const RpcMessage = z
|
|
25
|
+
.object({
|
|
26
|
+
jsonrpc: z.literal("2.0").describe("Always `2.0`."),
|
|
27
|
+
id: z
|
|
28
|
+
.union([z.string(), z.number()])
|
|
29
|
+
.optional()
|
|
30
|
+
.describe("The request's id. Absent on a notification, which gets no answer."),
|
|
31
|
+
method: z.string().min(1).describe("The method called, e.g. `tools/list`."),
|
|
32
|
+
params: z.record(z.string(), z.unknown()).optional().describe("The method's parameters."),
|
|
33
|
+
})
|
|
34
|
+
.describe("One JSON-RPC 2.0 request or notification.");
|
|
35
|
+
export type RpcMessage = z.infer<typeof RpcMessage>;
|
|
36
|
+
|
|
37
|
+
/** JSON-RPC's own error codes, the ones this server answers with. */
|
|
38
|
+
export const RPC_ERRORS = { methodNotFound: -32601, invalidParams: -32602, internal: -32603 } as const;
|
|
39
|
+
|
|
40
|
+
/** A tool as `tools/list` publishes it. */
|
|
41
|
+
export interface ListedTool {
|
|
42
|
+
readonly name: string;
|
|
43
|
+
readonly title: string;
|
|
44
|
+
readonly description: string;
|
|
45
|
+
readonly inputSchema: Record<string, unknown>;
|
|
46
|
+
readonly annotations: AppTool["annotations"] & { readonly title: string };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What a tool call came back with. */
|
|
50
|
+
export interface CallOutcome {
|
|
51
|
+
/** The route's status. */
|
|
52
|
+
readonly status: number;
|
|
53
|
+
/** The route's body, parsed when it was JSON. */
|
|
54
|
+
readonly body: unknown;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What the endpoint hands the protocol: the caller's tools, and a way to call one. */
|
|
58
|
+
export interface RpcHandlers {
|
|
59
|
+
/** The server's name and version, for `initialize`. */
|
|
60
|
+
readonly server: { readonly name: string; readonly version: string };
|
|
61
|
+
/** The tools this caller may call. */
|
|
62
|
+
readonly tools: () => Promise<readonly AppTool[]>;
|
|
63
|
+
/** Call one, as the caller. */
|
|
64
|
+
readonly call: (tool: AppTool, args: Record<string, unknown>) => Promise<CallOutcome>;
|
|
65
|
+
/** Told of a `tools/call` naming a tool the caller was not offered, before it is answered as unknown. */
|
|
66
|
+
readonly refused: (name: unknown) => Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A JSON-RPC answer, or `null` for a notification. */
|
|
70
|
+
export type RpcAnswer = { jsonrpc: "2.0"; id: string | number; result?: unknown; error?: unknown } | null;
|
|
71
|
+
|
|
72
|
+
/** A tool as `tools/list` publishes it. */
|
|
73
|
+
export function listedTool(tool: AppTool): ListedTool {
|
|
74
|
+
return {
|
|
75
|
+
name: tool.name,
|
|
76
|
+
title: tool.summary,
|
|
77
|
+
description: tool.description,
|
|
78
|
+
inputSchema: tool.inputSchema,
|
|
79
|
+
annotations: { title: tool.summary, ...tool.annotations },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The version to answer `initialize` with: the client's, when this server speaks it, or the newest. */
|
|
84
|
+
export function negotiatedVersion(requested: unknown): string {
|
|
85
|
+
return typeof requested === "string" && (MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requested)
|
|
86
|
+
? requested
|
|
87
|
+
: MCP_PROTOCOL_VERSIONS[0];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A call's outcome as an MCP tool result: the body as text, and as structured content when it is an object. */
|
|
91
|
+
export function toolResult(outcome: CallOutcome): Record<string, unknown> {
|
|
92
|
+
const text = typeof outcome.body === "string" ? outcome.body : JSON.stringify(outcome.body ?? null);
|
|
93
|
+
const structured =
|
|
94
|
+
outcome.body !== null && typeof outcome.body === "object" && !Array.isArray(outcome.body)
|
|
95
|
+
? { structuredContent: outcome.body }
|
|
96
|
+
: {};
|
|
97
|
+
return { content: [{ type: "text", text }], ...structured, isError: outcome.status >= 400 };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function record(value: unknown): Record<string, unknown> {
|
|
101
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Answer one message. */
|
|
105
|
+
export async function answer(message: RpcMessage, handlers: RpcHandlers): Promise<RpcAnswer> {
|
|
106
|
+
if (message.id === undefined) return null;
|
|
107
|
+
const id = message.id;
|
|
108
|
+
const ok = (result: unknown): RpcAnswer => ({ jsonrpc: "2.0", id, result });
|
|
109
|
+
const fail = (code: number, text: string): RpcAnswer => ({ jsonrpc: "2.0", id, error: { code, message: text } });
|
|
110
|
+
switch (message.method) {
|
|
111
|
+
case "initialize":
|
|
112
|
+
return ok({
|
|
113
|
+
protocolVersion: negotiatedVersion(message.params?.protocolVersion),
|
|
114
|
+
capabilities: { tools: { listChanged: false } },
|
|
115
|
+
serverInfo: handlers.server,
|
|
116
|
+
});
|
|
117
|
+
case "ping":
|
|
118
|
+
return ok({});
|
|
119
|
+
case "tools/list":
|
|
120
|
+
return ok({ tools: (await handlers.tools()).map(listedTool) });
|
|
121
|
+
case "tools/call": {
|
|
122
|
+
const name = message.params?.name;
|
|
123
|
+
// A tool the caller may not call is answered exactly as one that does not exist: the list it was offered
|
|
124
|
+
// never named it, so saying anything more would disclose it (§4.1).
|
|
125
|
+
const tool = (await handlers.tools()).find((entry) => entry.name === name);
|
|
126
|
+
if (tool === undefined) {
|
|
127
|
+
await handlers.refused(name);
|
|
128
|
+
return fail(RPC_ERRORS.invalidParams, `Unknown tool: ${String(name)}.`);
|
|
129
|
+
}
|
|
130
|
+
return ok(toolResult(await handlers.call(tool, record(message.params?.arguments))));
|
|
131
|
+
}
|
|
132
|
+
default:
|
|
133
|
+
return fail(RPC_ERRORS.methodNotFound, `Method not found: ${message.method}.`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { AuditEventInput, AuditOutcome } from "@pithy-sh/core/src/audit/auditEvent";
|
|
5
|
+
import { type AuditEmit, noopEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
6
|
+
import type { ArgumentClass } from "./argumentClass";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The audit row an in-Worker MCP tool call writes (`docs/AGENT-ACCESS.md` §9).
|
|
10
|
+
*
|
|
11
|
+
* **Who acted.** The call ran under the user's authority, so the row is `actorType: "user"` with their id — and
|
|
12
|
+
* `actorKind: "agent"`, the field control-plane rows already carry, so one filter finds every agent row on both
|
|
13
|
+
* paths. The client is in `metadata`: its id, and its name as it reported itself, which nothing has verified.
|
|
14
|
+
*
|
|
15
|
+
* **What it cost.** The route's status, the wall time from receiving the call to answering it, and the size of the
|
|
16
|
+
* route's response. CPU time is not readable per request in a Worker, so the row does not claim it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The action codes the MCP endpoint emits, under the `mcp` domain. */
|
|
20
|
+
export const McpAuditActions = {
|
|
21
|
+
/**
|
|
22
|
+
* One `tools/call`. Outcome `success`, `failure` when the route answered an error, or `denied` when the tool was
|
|
23
|
+
* never offered to the caller or the route refused them.
|
|
24
|
+
*/
|
|
25
|
+
toolCall: "mcp/tool_call",
|
|
26
|
+
} as const;
|
|
27
|
+
|
|
28
|
+
/** The longest tool name a row records. A name the caller made up is theirs to make as long as they like. */
|
|
29
|
+
export const MAX_TOOL_NAME = 128;
|
|
30
|
+
|
|
31
|
+
/** The longest client name a row records. The client chose its own name at registration. */
|
|
32
|
+
export const MAX_CLIENT_NAME = 128;
|
|
33
|
+
|
|
34
|
+
/** The tool a `tools/call` named, as a row records it: a string, bounded, or null. */
|
|
35
|
+
export function requestedToolName(name: unknown): string | null {
|
|
36
|
+
return typeof name === "string" ? name.slice(0, MAX_TOOL_NAME) : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The outcome a route's status records: a refusal is `denied`, any other error `failure`. */
|
|
40
|
+
export function toolCallOutcome(status: number): AuditOutcome {
|
|
41
|
+
if (status === 401 || status === 403) return "denied";
|
|
42
|
+
return status >= 400 ? "failure" : "success";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Who made a call: the user, the session the token was minted under, and the client acting for them. */
|
|
46
|
+
export interface ToolCallActor {
|
|
47
|
+
readonly userId: string;
|
|
48
|
+
readonly sessionId: string;
|
|
49
|
+
readonly clientId: string;
|
|
50
|
+
/** The client's name as it registered itself. Self-asserted; never verified. */
|
|
51
|
+
readonly clientReportedName: string | null;
|
|
52
|
+
/** The acting organization, or null where none is in force. */
|
|
53
|
+
readonly tenant: string | null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What ties the row to the rest of the request: the route's own rows carry the same `requestId`. */
|
|
57
|
+
export interface ToolCallCorrelation {
|
|
58
|
+
readonly requestId: string;
|
|
59
|
+
readonly ip: string | null;
|
|
60
|
+
readonly userAgent: string | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What came of a call: the route answered it, or it was never dispatched. */
|
|
64
|
+
export type ToolCallResult =
|
|
65
|
+
| {
|
|
66
|
+
readonly kind: "answered";
|
|
67
|
+
readonly status: number;
|
|
68
|
+
readonly responseBytes: number;
|
|
69
|
+
readonly arguments: ArgumentClass;
|
|
70
|
+
}
|
|
71
|
+
/** `withheld`: a tool this app has that the caller's role was not offered. `unknown`: no such tool. */
|
|
72
|
+
| { readonly kind: "refused"; readonly reason: "withheld" | "unknown" };
|
|
73
|
+
|
|
74
|
+
/** Everything one row is built from. */
|
|
75
|
+
export interface ToolCallRecord {
|
|
76
|
+
readonly actor: ToolCallActor;
|
|
77
|
+
readonly correlation: ToolCallCorrelation;
|
|
78
|
+
/** The tool's name, or null when the call named none. */
|
|
79
|
+
readonly tool: string | null;
|
|
80
|
+
readonly durationMs: number;
|
|
81
|
+
readonly result: ToolCallResult;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The audit event for one tool call. */
|
|
85
|
+
export function toolCallEvent(record: ToolCallRecord): AuditEventInput {
|
|
86
|
+
const { actor, correlation, tool, durationMs, result } = record;
|
|
87
|
+
const outcome = result.kind === "answered" ? toolCallOutcome(result.status) : "denied";
|
|
88
|
+
const client = {
|
|
89
|
+
clientId: actor.clientId,
|
|
90
|
+
clientReportedName: actor.clientReportedName?.slice(0, MAX_CLIENT_NAME) ?? null,
|
|
91
|
+
};
|
|
92
|
+
const metadata =
|
|
93
|
+
result.kind === "answered"
|
|
94
|
+
? {
|
|
95
|
+
tool,
|
|
96
|
+
...client,
|
|
97
|
+
status: result.status,
|
|
98
|
+
durationMs,
|
|
99
|
+
responseBytes: result.responseBytes,
|
|
100
|
+
arguments: result.arguments,
|
|
101
|
+
}
|
|
102
|
+
: { tool, ...client, status: null, durationMs, responseBytes: null, refused: result.reason };
|
|
103
|
+
return {
|
|
104
|
+
action: McpAuditActions.toolCall,
|
|
105
|
+
outcome,
|
|
106
|
+
severity: outcome === "denied" ? "warning" : "info",
|
|
107
|
+
actorType: "user",
|
|
108
|
+
actorId: actor.userId,
|
|
109
|
+
actorKind: "agent",
|
|
110
|
+
sessionId: actor.sessionId,
|
|
111
|
+
tenant: actor.tenant,
|
|
112
|
+
resourceType: "mcp_tool",
|
|
113
|
+
resourceId: tool,
|
|
114
|
+
requestId: correlation.requestId,
|
|
115
|
+
ip: correlation.ip,
|
|
116
|
+
userAgent: correlation.userAgent,
|
|
117
|
+
metadata,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Write one row, and never fail the call it records: the row is evidence of what happened, never part of making it
|
|
123
|
+
* happen. With no audit capability composed the event is not even built, since building it reads the client's row.
|
|
124
|
+
*/
|
|
125
|
+
export async function recordToolCall(emit: AuditEmit, build: () => Promise<AuditEventInput>): Promise<void> {
|
|
126
|
+
if (emit === noopEmit) return;
|
|
127
|
+
try {
|
|
128
|
+
await emit(await build());
|
|
129
|
+
} catch {
|
|
130
|
+
// The seam's own recorder swallows and logs its failures; this covers an emitter or a lookup that does not.
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type Kysely, type SqlBool, sql } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The one index this adds: at most one `purged` row per account. */
|
|
8
|
+
const PURGED_ONCE_INDEX = "pithyAuthUserLifecyclePurgedOnceIdx";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The purge, once (#622): what a deletion asked of its last mail, and a constraint that a purge finishes once.
|
|
12
|
+
*
|
|
13
|
+
* **`notify` on `pithy_auth_user_lifecycle`.** A hard deletion with `notify: false` asks the purge to send no
|
|
14
|
+
* deletion-complete mail, and the purge that sends it is not always the one the deletion started: with no
|
|
15
|
+
* purge Workflow bound, or a start that failed, the daily pass starts it, and the pass has no request to read
|
|
16
|
+
* the choice from. So the deletion's own history row carries it, and the purge reads it there. `1` or `0` on a
|
|
17
|
+
* hard deletion's `deleted` row that named it; null on every other row, and on one that did not.
|
|
18
|
+
*
|
|
19
|
+
* **A unique partial index on `userId` where `action` is `purged`.** Two purges of one account can overlap —
|
|
20
|
+
* the daily pass and a hard deletion's own, or a purge still retrying when the next pass starts another — and
|
|
21
|
+
* both reach `complete`. A read-then-insert lets both write the record, and both fire `onUserPurged`. With the
|
|
22
|
+
* index the insert is the check: the one that lands fires, the other finds the row there and does nothing.
|
|
23
|
+
*
|
|
24
|
+
* **A `0005`, appended.** `0004` has shipped. No backfill, and no duplicate to clean up first: nothing before
|
|
25
|
+
* this release ran a purge, so no account has a `purged` row yet.
|
|
26
|
+
*/
|
|
27
|
+
export const auth_0005_purge_once: Migration = {
|
|
28
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
29
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("notify", "integer").execute();
|
|
30
|
+
await db.schema
|
|
31
|
+
.createIndex(PURGED_ONCE_INDEX)
|
|
32
|
+
.on("pithyAuthUserLifecycle")
|
|
33
|
+
.column("userId")
|
|
34
|
+
.unique()
|
|
35
|
+
.where(sql<SqlBool>`action = 'purged'`)
|
|
36
|
+
.execute();
|
|
37
|
+
},
|
|
38
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
39
|
+
await db.schema.dropIndex(PURGED_ONCE_INDEX).execute();
|
|
40
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("notify").execute();
|
|
41
|
+
},
|
|
42
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { Kysely } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The window read's index: rows issued in a range, newest first, the id ordering a millisecond's ties. */
|
|
8
|
+
const ISSUED_INDEX = "pithyAuthVerificationOutcomesIssuedAtIdx";
|
|
9
|
+
/** How a use finds the row it stamps, and how a wrong code's re-issue moves it. */
|
|
10
|
+
const VERIFICATION_INDEX = "pithyAuthVerificationOutcomesVerificationIdIdx";
|
|
11
|
+
/** How a purge finds an account's rows. */
|
|
12
|
+
const USER_INDEX = "pithyAuthVerificationOutcomesUserIdIdx";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The verification ledger (#829): `pithy_auth_verification_outcomes`, one row per sign-in link or code auth
|
|
16
|
+
* issues, stamped when it is used. See `../data/verificationOutcome.ts` for why it exists and what it never holds.
|
|
17
|
+
*
|
|
18
|
+
* **Every date is `integer`**, ms-epoch: nothing but the kit writes this table. **No backfill**: the links and
|
|
19
|
+
* codes issued before this ran left nothing to read back — a used one was deleted on use — so the ledger starts
|
|
20
|
+
* empty, and a window reaching back before the upgrade counts only what was issued after it.
|
|
21
|
+
*
|
|
22
|
+
* **A `0006`, appended.** `@pithy-sh/auth` has shipped, so its chain is history.
|
|
23
|
+
*/
|
|
24
|
+
export const auth_0006_verification_outcomes: Migration = {
|
|
25
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
26
|
+
await db.schema
|
|
27
|
+
.createTable("pithyAuthVerificationOutcomes")
|
|
28
|
+
.addColumn("id", "integer", (c) => c.primaryKey().autoIncrement())
|
|
29
|
+
.addColumn("verificationId", "text", (c) => c.notNull())
|
|
30
|
+
.addColumn("type", "text", (c) => c.notNull())
|
|
31
|
+
.addColumn("userId", "text")
|
|
32
|
+
.addColumn("emailJobId", "text")
|
|
33
|
+
.addColumn("issuedAt", "integer", (c) => c.notNull())
|
|
34
|
+
.addColumn("expiresAt", "integer", (c) => c.notNull())
|
|
35
|
+
.addColumn("usedAt", "integer")
|
|
36
|
+
.execute();
|
|
37
|
+
await db.schema.createIndex(ISSUED_INDEX).on("pithyAuthVerificationOutcomes").columns(["issuedAt", "id"]).execute();
|
|
38
|
+
await db.schema
|
|
39
|
+
.createIndex(VERIFICATION_INDEX)
|
|
40
|
+
.on("pithyAuthVerificationOutcomes")
|
|
41
|
+
.column("verificationId")
|
|
42
|
+
.execute();
|
|
43
|
+
await db.schema.createIndex(USER_INDEX).on("pithyAuthVerificationOutcomes").column("userId").execute();
|
|
44
|
+
},
|
|
45
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
46
|
+
await db.schema.dropIndex(USER_INDEX).execute();
|
|
47
|
+
await db.schema.dropIndex(VERIFICATION_INDEX).execute();
|
|
48
|
+
await db.schema.dropIndex(ISSUED_INDEX).execute();
|
|
49
|
+
await db.schema.dropTable("pithyAuthVerificationOutcomes").execute();
|
|
50
|
+
},
|
|
51
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type Kysely, type SqlBool, sql } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The period read's index: every erasure row written in a window. */
|
|
8
|
+
const CREATED_INDEX = "pithyAuthUserLifecycleCreatedAtIdx";
|
|
9
|
+
|
|
10
|
+
/** The period read's other index: every deletion whose purge came due in a window. */
|
|
11
|
+
const PURGE_AFTER_INDEX = "pithyAuthUserLifecyclePurgeAfterIdx";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The erasure record (#823): what a deletion asked for, kept where the purge cannot erase it.
|
|
15
|
+
*
|
|
16
|
+
* **`mode` and `purge_after` on `pithy_auth_user_lifecycle`.** The attestation says whether a deletion was soft or
|
|
17
|
+
* hard and when its purge came due. Both sat only on `pithy_auth_users`, as `purgeAfter`, or nowhere, and the purge
|
|
18
|
+
* erases that row. So a `deleted` row now carries them: `soft` or `hard`, and the instant, ms-epoch. Null on every
|
|
19
|
+
* other row, and on a deletion recorded before this ran — the attestation says so rather than guessing.
|
|
20
|
+
*
|
|
21
|
+
* **Two indexes for the period read**, which asks which purges came due, ran a step, failed or finished in a window.
|
|
22
|
+
*
|
|
23
|
+
* **A `0007`, appended.** `@pithy-sh/auth` has shipped, so its chain is history. No backfill.
|
|
24
|
+
*/
|
|
25
|
+
export const auth_0007_erasure_record: Migration = {
|
|
26
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
27
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("mode", "text").execute();
|
|
28
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("purgeAfter", "integer").execute();
|
|
29
|
+
await db.schema.createIndex(CREATED_INDEX).on("pithyAuthUserLifecycle").column("createdAt").execute();
|
|
30
|
+
await db.schema
|
|
31
|
+
.createIndex(PURGE_AFTER_INDEX)
|
|
32
|
+
.on("pithyAuthUserLifecycle")
|
|
33
|
+
.column("purgeAfter")
|
|
34
|
+
.where(sql<SqlBool>`purge_after is not null`)
|
|
35
|
+
.execute();
|
|
36
|
+
},
|
|
37
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
38
|
+
await db.schema.dropIndex(PURGE_AFTER_INDEX).execute();
|
|
39
|
+
await db.schema.dropIndex(CREATED_INDEX).execute();
|
|
40
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("purgeAfter").execute();
|
|
41
|
+
await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("mode").execute();
|
|
42
|
+
},
|
|
43
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { type Kysely, sql } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/** The inactivity pass's index: every account by when it was last active. */
|
|
8
|
+
const LAST_ACTIVE_INDEX = "pithyAuthUsersLastActiveAtIdx";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* When an account was last active — stamped on `pithy_auth_users` by every session the account opens, so the
|
|
12
|
+
* retention policy's class ages have a clock that a sign-out cannot erase: a session row goes when its holder signs
|
|
13
|
+
* out, and this column stays.
|
|
14
|
+
*
|
|
15
|
+
* **Every existing account starts its clock now.** A row written before this column existed has no record of its
|
|
16
|
+
* last sign-in, and reading its absence as "never" would soft-delete an account somebody used last week the first
|
|
17
|
+
* night the pass runs. So `up` stamps the migration's own instant on every row, and an account becomes inactive no
|
|
18
|
+
* sooner than its class age after the upgrade. `down` drops the column and the index.
|
|
19
|
+
*/
|
|
20
|
+
export const auth_0008_last_active: Migration = {
|
|
21
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
22
|
+
await db.schema.alterTable("pithyAuthUsers").addColumn("lastActiveAt", "integer").execute();
|
|
23
|
+
await sql`update pithy_auth_users set last_active_at = cast(strftime('%s', 'now') as integer) * 1000`.execute(db);
|
|
24
|
+
await db.schema.createIndex(LAST_ACTIVE_INDEX).on("pithyAuthUsers").column("lastActiveAt").execute();
|
|
25
|
+
},
|
|
26
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
27
|
+
await db.schema.dropIndex(LAST_ACTIVE_INDEX).execute();
|
|
28
|
+
await db.schema.alterTable("pithyAuthUsers").dropColumn("lastActiveAt").execute();
|
|
29
|
+
},
|
|
30
|
+
};
|