@pithy-sh/auth 0.11.0 → 0.12.1
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/audit/actions.d.ts +39 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +40 -1
- package/dist/audit/emit.d.ts +34 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +47 -1
- package/dist/audit/evidence.d.ts +8 -2
- package/dist/audit/evidence.d.ts.map +1 -1
- package/dist/capability.d.ts +31 -11
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- 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 +25 -4
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +9 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +6 -2
- 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 +56 -10
- package/dist/http/csrf.d.ts.map +1 -1
- package/dist/http/csrf.js +2 -1
- package/dist/http/guards.d.ts +15 -11
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +46 -11
- 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 +12 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +25 -4
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +9 -3
- package/dist/http/responses.d.ts +142 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +66 -10
- package/dist/http/routes.d.ts +2 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +35 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +44 -1
- package/dist/http/views.d.ts +22 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +40 -4
- 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 +86 -41
- 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/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/transitions.d.ts +22 -1
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +51 -4
- 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/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/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -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 +20 -5
- package/dist/purge/contribution.d.ts.map +1 -1
- package/dist/purge/contribution.js +20 -6
- package/dist/purge/run.d.ts +75 -5
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +117 -14
- package/dist/purge/workflow.d.ts +15 -2
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +51 -7
- package/dist/test-utils/accountFootprint.d.ts +5 -2
- package/dist/test-utils/accountFootprint.d.ts.map +1 -1
- package/dist/test-utils/accountFootprint.js +7 -2
- 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 +59 -7
- 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 +39 -0
- package/src/audit/emit.ts +63 -0
- package/src/audit/evidence.ts +8 -4
- package/src/capability.ts +80 -23
- 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 +15 -3
- package/src/data/verificationOutcome.ts +86 -0
- package/src/email/send.ts +2 -2
- package/src/http/adminRoutes.ts +68 -3
- package/src/http/csrf.ts +4 -1
- package/src/http/guards.ts +48 -11
- package/src/http/handoff.ts +350 -0
- package/src/http/middleware.ts +29 -3
- package/src/http/resolve.ts +25 -25
- package/src/http/responses.ts +134 -8
- package/src/http/routes.ts +63 -4
- package/src/http/schemas.ts +85 -0
- package/src/http/views.ts +46 -2
- package/src/index.ts +2 -0
- package/src/instance/auth.ts +51 -1
- package/src/instance/plugins.ts +20 -2
- package/src/ledger/read.ts +133 -0
- package/src/ledger/record.ts +198 -0
- package/src/lifecycle/erasure.ts +118 -0
- package/src/lifecycle/inactivity.ts +56 -0
- package/src/lifecycle/transitions.ts +75 -5
- 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/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/set.ts +7 -1
- package/src/processing/activities.ts +14 -0
- package/src/purge/contribution.ts +37 -10
- package/src/purge/run.ts +179 -16
- package/src/purge/workflow.ts +65 -7
- package/src/seeds/example.ts +2 -2
- package/src/test-utils/accountFootprint.ts +10 -1
- 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,136 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { Verification } from "../data/betterAuth.js";
|
|
4
|
+
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { sqliteJson } from "@pithy-sh/core/src/data/codecs";
|
|
7
|
+
import { sha256Base64Url, timingSafeEqual } from "@pithy-sh/core/src/controlPlane/token/digest";
|
|
8
|
+
//#region src/token/handoff.ts
|
|
9
|
+
/**
|
|
10
|
+
* The one-time code that hands a redirect sign-in back to a native app.
|
|
11
|
+
*
|
|
12
|
+
* A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
|
|
13
|
+
* cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
|
|
14
|
+
* this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
|
|
15
|
+
*
|
|
16
|
+
* **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
|
|
17
|
+
* cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
|
|
18
|
+
* read off a URL log, or caught by another app claiming the same scheme, is still worth something.
|
|
19
|
+
*
|
|
20
|
+
* **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
|
|
21
|
+
* nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
|
|
22
|
+
* names the session by id, never by token, so the table holds no credential at all.
|
|
23
|
+
*
|
|
24
|
+
* **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
|
|
25
|
+
* app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
|
|
26
|
+
* code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
|
|
27
|
+
* the code is worth nothing to it. A code is never issued without a challenge.
|
|
28
|
+
*
|
|
29
|
+
* The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
|
|
30
|
+
* one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
|
|
31
|
+
* many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
|
|
32
|
+
* also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
|
|
33
|
+
*/
|
|
34
|
+
const HANDOFF_TTL_SECONDS = 60;
|
|
35
|
+
/** The most lapsed codes one issue deletes. The next issue takes the rest. */
|
|
36
|
+
const HANDOFF_SWEEP_LIMIT = 50;
|
|
37
|
+
/** The identifier prefix that keeps these rows apart from every other verification. */
|
|
38
|
+
const IDENTIFIER_PREFIX = "pithy-handoff:";
|
|
39
|
+
/** An S256 challenge: the base64url SHA-256 of a verifier, unpadded, which is always 43 characters. */
|
|
40
|
+
const CHALLENGE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
|
|
41
|
+
/** An RFC 7636 code verifier: 43 to 128 characters, each unreserved (`A-Z a-z 0-9 - . _ ~`). */
|
|
42
|
+
const VERIFIER_SHAPE = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
43
|
+
/** Whether a value has the shape RFC 7636 gives a code verifier. */
|
|
44
|
+
function isHandoffVerifier(value) {
|
|
45
|
+
return VERIFIER_SHAPE.test(value);
|
|
46
|
+
}
|
|
47
|
+
/** Whether a value has the shape of an S256 challenge. */
|
|
48
|
+
function isHandoffChallenge(value) {
|
|
49
|
+
return CHALLENGE_SHAPE.test(value);
|
|
50
|
+
}
|
|
51
|
+
/** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
|
|
52
|
+
function handoffChallengeOf(verifier) {
|
|
53
|
+
return sha256Base64Url(new TextEncoder().encode(verifier));
|
|
54
|
+
}
|
|
55
|
+
/** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
|
|
56
|
+
const StoredHandoff = z.object({
|
|
57
|
+
sessionId: z.string().describe("The id of the session the code stands for. Never its token."),
|
|
58
|
+
challenge: z.string().regex(CHALLENGE_SHAPE).describe("The S256 challenge the app sent with the sign-in. The trade's verifier must hash to it.")
|
|
59
|
+
}).describe("A handoff code's row value: the session and the challenge that binds the code to one app.");
|
|
60
|
+
/** The `value` column as a handoff: JSON text in SQLite, validated both ways. */
|
|
61
|
+
const StoredHandoffValue = sqliteJson(StoredHandoff);
|
|
62
|
+
async function identifierOf(code) {
|
|
63
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code));
|
|
64
|
+
const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
65
|
+
return `${IDENTIFIER_PREFIX}${hex}`;
|
|
66
|
+
}
|
|
67
|
+
function randomCode() {
|
|
68
|
+
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
|
|
69
|
+
let binary = "";
|
|
70
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
71
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
72
|
+
}
|
|
73
|
+
/** Delete up to {@link HANDOFF_SWEEP_LIMIT} codes that lapsed by `now`. */
|
|
74
|
+
async function sweepLapsed(db, now) {
|
|
75
|
+
await db.deleteFrom("pithyAuthVerifications").where("id", "in", (lapsed) => lapsed.selectFrom("pithyAuthVerifications").select("id").where("identifier", "like", `${IDENTIFIER_PREFIX}%`).where("expiresAt", "<=", Verification.shape.expiresAt.encode(now)).limit(50)).execute();
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
|
|
79
|
+
* other shape throws: an unbound code is never written.
|
|
80
|
+
*/
|
|
81
|
+
async function issueHandoff(db, input) {
|
|
82
|
+
if (!isHandoffChallenge(input.challenge)) throw new InternalError({ detail: "a handoff code was asked for without an S256 challenge to bind it to" });
|
|
83
|
+
await sweepLapsed(db, input.now);
|
|
84
|
+
const code = randomCode();
|
|
85
|
+
const expiresAt = new Date(input.now.getTime() + 6e4);
|
|
86
|
+
await db.insertInto("pithyAuthVerifications").values(Verification.encode({
|
|
87
|
+
id: crypto.randomUUID(),
|
|
88
|
+
identifier: await identifierOf(code),
|
|
89
|
+
value: z.string().parse(StoredHandoffValue.encode({
|
|
90
|
+
sessionId: input.sessionId,
|
|
91
|
+
challenge: input.challenge
|
|
92
|
+
})),
|
|
93
|
+
expiresAt,
|
|
94
|
+
createdAt: input.now,
|
|
95
|
+
updatedAt: input.now
|
|
96
|
+
})).execute();
|
|
97
|
+
return {
|
|
98
|
+
code,
|
|
99
|
+
expiresAt
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
|
|
104
|
+
* presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
|
|
105
|
+
*/
|
|
106
|
+
async function redeemHandoff(db, input, now) {
|
|
107
|
+
const row = await db.deleteFrom("pithyAuthVerifications").where("identifier", "=", await identifierOf(input.code)).returning(["value", "expiresAt"]).executeTakeFirst();
|
|
108
|
+
if (!row) return {
|
|
109
|
+
ok: false,
|
|
110
|
+
reason: "unknown"
|
|
111
|
+
};
|
|
112
|
+
const parsed = StoredHandoffValue.safeParse(row.value);
|
|
113
|
+
if (!parsed.success) return {
|
|
114
|
+
ok: false,
|
|
115
|
+
reason: "unknown"
|
|
116
|
+
};
|
|
117
|
+
const stored = parsed.data;
|
|
118
|
+
if (Verification.shape.expiresAt.parse(row.expiresAt).getTime() <= now.getTime()) return {
|
|
119
|
+
ok: false,
|
|
120
|
+
reason: "expired"
|
|
121
|
+
};
|
|
122
|
+
if (!isHandoffVerifier(input.verifier)) return {
|
|
123
|
+
ok: false,
|
|
124
|
+
reason: "malformed"
|
|
125
|
+
};
|
|
126
|
+
if (!timingSafeEqual(await handoffChallengeOf(input.verifier), stored.challenge)) return {
|
|
127
|
+
ok: false,
|
|
128
|
+
reason: "mismatch"
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
ok: true,
|
|
132
|
+
sessionId: stored.sessionId
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
136
|
+
export { HANDOFF_SWEEP_LIMIT, HANDOFF_TTL_SECONDS, StoredHandoff, handoffChallengeOf, isHandoffChallenge, isHandoffVerifier, issueHandoff, redeemHandoff };
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
/** This package's npm name — the join key against a release feed. */
|
|
4
4
|
export declare const PACKAGE_NAME = "@pithy-sh/auth";
|
|
5
5
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
6
|
-
export declare const PACKAGE_VERSION = "0.
|
|
6
|
+
export declare const PACKAGE_VERSION = "0.12.1";
|
|
7
7
|
//# sourceMappingURL=version.generated.d.ts.map
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
/** This package's npm name — the join key against a release feed. */
|
|
5
5
|
const PACKAGE_NAME = "@pithy-sh/auth";
|
|
6
6
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
7
|
-
const PACKAGE_VERSION = "0.
|
|
7
|
+
const PACKAGE_VERSION = "0.12.1";
|
|
8
8
|
//#endregion
|
|
9
9
|
export { PACKAGE_NAME, PACKAGE_VERSION };
|
|
@@ -13,6 +13,8 @@ Both live on `pithy_auth_users`, so a session read already carries them. An acco
|
|
|
13
13
|
|
|
14
14
|
No client can write its own state. The four columns are `input: false`, and only the kit's transitions set them.
|
|
15
15
|
|
|
16
|
+
**The admin reads say where each account stands.** `GET /auth/admin/users` and `GET /auth/admin/users/:userId` return each user with `state` — `active`, `suspended` or `deleted` — `suspendedUntil`, the end of a suspension in force or null for one with none and in every other state, and `purgeAfter`, the last day a deleted account can be restored or null otherwise. They are read the way enforcement reads them, so a suspension past its end is `active`. The listing does not leave a suspended or deleted account out, and these are what let a pane offer suspend or reinstate without sending a write to find out. Neither the reason nor who acted is there: the reason is on the trail, and the trail is audit's. Each field is optional in `AdminUserView`, so a client reading a Worker older than them still parses its answer.
|
|
17
|
+
|
|
16
18
|
## Enforcement
|
|
17
19
|
|
|
18
20
|
A refused request gets one of two errors, both 403:
|
|
@@ -40,7 +42,7 @@ A transition that finds the account already where it was asked to put it does no
|
|
|
40
42
|
|
|
41
43
|
Suspending an account that is already suspended is the one exception. It restates the suspension: the new reason and end replace the old, a row records them, and the mail and the audit event go out. The start stays, and no hook fires, because the account was suspended and still is.
|
|
42
44
|
|
|
43
|
-
Each transition also writes an audit event: `auth/admin_user_suspended`, `auth/admin_user_reinstated`, `auth/admin_user_soft_deleted`, `auth/admin_user_hard_deleted`, `auth/admin_user_restored`, `auth/admin_user_purged`, and `auth/user_self_deleted` when the account's holder deletes it. An export writes `auth/admin_user_exported`.
|
|
45
|
+
Each transition also writes an audit event: `auth/admin_user_suspended`, `auth/admin_user_reinstated`, `auth/admin_user_soft_deleted`, `auth/admin_user_hard_deleted`, `auth/admin_user_restored`, `auth/admin_user_purged`, and `auth/user_self_deleted` when the account's holder deletes it. A purge adds `auth/admin_user_purge_step` per step and `auth/admin_user_purge_failed` when it gives up. An export writes `auth/admin_user_exported`.
|
|
44
46
|
|
|
45
47
|
## Scopes
|
|
46
48
|
|
|
@@ -85,13 +87,15 @@ GET /auth/admin/users/:userId/export?reason=…
|
|
|
85
87
|
|
|
86
88
|
`reason` is required on all three, on the same terms as a suspension's. A request without one is `validation/invalid_input`.
|
|
87
89
|
|
|
88
|
-
**Two modes, and soft is the default.** `mode: "soft"`, or no mode at all, stamps `deleted_at` and `purge_after` — now plus
|
|
90
|
+
**Two modes, and soft is the default.** `mode: "soft"`, or no mode at all, stamps `deleted_at` and `purge_after` — now plus the purge window — and revokes every session the account holds. Signing in again answers `auth/account_deleted`. The deletion-scheduled mail goes out with the purge date and, when you configure one, the restore path. `onUserDeleted` fires. The account can be restored until `purge_after`. `mode: "hard"` closes the window now: `purge_after` is the moment of the deletion, nothing can restore it, and the purge starts in the same call. You name it on purpose. A typo — `"Hard"`, `"hrad"` — is a 400, never either mode. A hard deletion of an account already deleted softly brings its purge forward to now.
|
|
91
|
+
|
|
92
|
+
**The purge window** is `retention.purgeWindows.user` from the Worker's `retention` block in `pithy.config.ts` when it names one, and otherwise auth's own `retention.purgeAfterDays`, 30 unless you set it. The block, and everything else it governs, is [`docs/CONTROL-PLANE.md`](../../../docs/CONTROL-PLANE.md#retention-and-legal-holds).
|
|
89
93
|
|
|
90
94
|
The response says what happened: `outcome` is `deleted`, `brought_forward`, or `unchanged` for an account already deleted. `purge` is `scheduled` for a soft deletion, `started` when this call started the purge, and `pending` when the account is due and this Worker binds no purge Workflow to start. `notify: false` silences the mail this call sends: the deletion-scheduled notice for soft, the deletion-complete notice for hard.
|
|
91
95
|
|
|
92
96
|
**Restore** clears both columns inside the window and records it. The person signs in again; no session comes back. A suspension the account was under before the deletion is still there, and the response says `state: "suspended"`. Once `purge_after` has passed the purge is due, so a restore is a 409 naming the date. The window is checked against the database's clock as the restore's write runs, the same clock the purge checks it against, so a restore and a purge that race always agree on which one won. A window that closes while a restore is in flight, or that a hard deletion brings forward, is the same 409. After the purge there is no account: a 404, whose action says the data is gone.
|
|
93
97
|
|
|
94
|
-
**Export** answers an access request. It returns one JSON document, validated by `AdminUserExportResponse` from `@pithy-sh/auth/src/http/responses`: the subject, when it was read, and one entry per composed capability that declares a purge contribution, in the order the purge
|
|
98
|
+
**Export** answers an access request. It returns one JSON document, validated by `AdminUserExportResponse` from `@pithy-sh/auth/src/http/responses`: the subject, when it was read, and one entry per composed capability that declares a purge contribution, in the order the purge runs them. Each entry says what a purge does with its rows — `disposition` is `erase` or `retain`, and a `retain` entry carries the `basis` it is kept on, in the sentence written for the person — and then what it answered: `exported` with that capability's data, `not_exported` when it erases rows it does not say how to export, or `unavailable` when its rows would not read. Every kit capability that holds rows about a person exports them, so `not_exported` is only ever an adopter's own capability; [what each one does](#what-each-capability-does-with-a-persons-rows) is below. Auth's own part is `AuthUserExport`: the account, its sessions, linked providers, devices, history, the sign-in links and codes the verification ledger records for it, and its rows in the user-keyed tables its Better Auth plugins created, and no credential — no session token, no provider token, no push token, no two-factor secret or backup code, no key. No kit capability's part carries one either: no opt-in token, no share link, no invitation digest, no provider payload, no Google Play purchase token, no message variables. It is audited as a disclosure, `auth/admin_user_exported`, with the operator, the reason, and which parts answered, never the data. An unknown or purged account is a 404.
|
|
95
99
|
|
|
96
100
|
Every call is audited, as for suspend and reinstate: a deletion under `auth/admin_user_soft_deleted` or `auth/admin_user_hard_deleted`, a restore under `auth/admin_user_restored`, with the operator, the connection, the reason and the user id. A refusal is `denied` with its code, and a call that changed nothing is a success with `changed: false`.
|
|
97
101
|
|
|
@@ -111,16 +115,22 @@ It is always soft, on the configured window, and the subject is always the sessi
|
|
|
111
115
|
|
|
112
116
|
## The purge
|
|
113
117
|
|
|
114
|
-
A purge erases one deleted account from every capability that holds rows about it. It runs as a Workflow, **one step per composed purge contribution**, named for its capability, so a capability that fails retries alone and the steps that finished are not run again. Each step records that it ran in `pithy_auth_user_lifecycle`, with the contribution's summary. The order:
|
|
118
|
+
A purge erases one deleted account from every capability that holds rows about it. It runs as a Workflow, **one step per composed purge contribution**, named for its capability, so a capability that fails retries alone and the steps that finished are not run again. Each step records that it ran in `pithy_auth_user_lifecycle`, with the contribution's summary. A contribution that **retains** its rows is a step too, and erases nothing: it records `purge_retained`, with the basis it gave as the reason, so the history never reads a kept step as an erased one. The order:
|
|
115
119
|
|
|
116
120
|
1. Is the account due — deleted, with its window closed? A restored account, one inside its window, and one already erased end the run here, having erased nothing. Re-running a purge for the same subject exits without error.
|
|
117
|
-
2. Every composed contribution but auth's, in composition order, your `app` last.
|
|
121
|
+
2. Every composed contribution but auth's, in composition order, your `app` last. Each reads the account's address, when it needs one, inside its own step.
|
|
118
122
|
3. The deletion-complete mail, **before the address is erased**: auth's rows, which hold it, are still there.
|
|
119
|
-
4. Auth's own: the user row, its sessions, linked providers, devices, refresh-token ledger
|
|
123
|
+
4. Auth's own: the user row, its sessions, linked providers, devices, refresh-token ledger, pending sign-in codes and its rows in the verification ledger, and its rows in every table a composed Better Auth plugin created with a `userId` column — a two-factor secret and its backup codes, a passkey, an API key. Its history stays — the one `pithy_auth_*` row left.
|
|
120
124
|
5. The `purged` record, `auth/admin_user_purged`, and `onUserPurged`, once — even when two purges of one account overlap.
|
|
121
125
|
|
|
126
|
+
**A legal hold stops it.** Before the first step, and again before every step after it, the purge asks whether a hold stands on the account, each ask its own step. A hold found ends the run as `held`: the steps that finished stay finished, and nothing more is erased. Released, the account is still deleted and still due, so the next daily pass starts a fresh purge, whose steps find nothing to erase where the first one did and carry on from there. A hold that cannot be read fails its step, which retries, so a purge never erases past a hold it could not see. The daily pass does not start a purge for a held account at all. Holds are placed over the control plane: [`docs/CONTROL-PLANE.md`](../../../docs/CONTROL-PLANE.md#retention-and-legal-holds).
|
|
127
|
+
|
|
128
|
+
Every step from 2 on also records an audit event, `auth/admin_user_purge_step`, with the step's name and whether it erased or retained in its metadata, and never the summary. A step that runs out of retries fails the instance, and before it does the purge records where: a `purge_failed` row naming the step, and `auth/admin_user_purge_failed`. The failure's message is never written. The `deleted` row keeps the deletion's mode and when its purge comes due, because the purge erases the account's own columns. Together they are what [the erasure attestation](../../../docs/CONTROL-PLANE.md#erasure) reads: `GET /control-plane/erasure/user/:userId`, under `erasure:read`.
|
|
129
|
+
|
|
122
130
|
A daily cron at 02:00 UTC starts the purge for every account past its `purge_after`, and for none before it. A hard deletion starts its own. Either way the instance is named for the deletion and the UTC day, so a hard deletion repeated, or one the daily pass also finds due, is one purge, and a purge that failed is started again by the next day's pass. A hard deletion's `notify: false` is saved with the deletion, so it holds when the daily pass is the one that starts its purge.
|
|
123
131
|
|
|
132
|
+
**Inactivity deletes an account, through this same lifecycle.** When the Worker's `retention` block declares class ages (`classAges: { pii: "3y" }`), the same daily pass soft-deletes every account untouched for longer than the strictest class age it holds: no sign-in, no token refresh, and no session refreshed since. Auth marks an account's `name` and `email` as `pii`, so a `pii` age reaches every account. The clock is `lastActiveAt` on the account, stamped each time it opens a session or refreshes one, and stamped on every existing account when the column arrived. The deletion is an ordinary soft one by a `system` actor, with the reason *Inactive for more than N days, the retention policy's limit for the personal data it holds*: the deletion-scheduled mail, the purge window, then the purge. Which classes an account holds is read off the composed schemas that hold rows about a user. A held account is skipped. A pass deletes at most 200 accounts, so a backlog drains over several nights. With no class age that applies, the pass does nothing.
|
|
133
|
+
|
|
124
134
|
The `scheduled` handler starts only the jobs whose `schedule` is the cron that fired, so the daily pass runs once a day even in a Worker whose other jobs run hourly.
|
|
125
135
|
|
|
126
136
|
**The Workflows are yours to export.** A purge runs every composed capability's contribution, your own among them, and only the Worker that composes auth has them. So the two classes are five lines each in that Worker's entry, beside `createEntrypoint`, and their bodies are the kit's:
|
|
@@ -190,7 +200,34 @@ Each fires once per transition. A call that finds the account already where it a
|
|
|
190
200
|
|
|
191
201
|
## Screens
|
|
192
202
|
|
|
193
|
-
Three screens ship with auth and are yours after `pithy ui add react`: account suspended, account deleted, and organization suspended. Each says what happened, what it means, and who to ask, in its own English. None renders a reason or a date from its URL, because anybody can write a URL. The details are in the mail.
|
|
203
|
+
Three screens ship with auth and are yours after `pithy ui add react`, or in React Native primitives after `pithy ui add react-native`: account suspended, account deleted, and organization suspended. Each says what happened, what it means, and who to ask, in its own English. None renders a reason or a date from its URL, because anybody can write a URL. The details are in the mail.
|
|
204
|
+
|
|
205
|
+
## What each capability does with a person's rows
|
|
206
|
+
|
|
207
|
+
Every kit capability that holds rows about a person declares a `user` contribution, and every one exports what it holds. Most erase. Four keep their rows, because the law or the record needs them, and say why.
|
|
208
|
+
|
|
209
|
+
| Capability | Disposition | What |
|
|
210
|
+
|---|---|---|
|
|
211
|
+
| `auth` | erase | The account, sessions, providers, devices, refresh-token ledger, pending codes, verification ledger, plugin rows. Its lifecycle history stays. |
|
|
212
|
+
| `mcp` | erase | The consents the person gave applications to act as them, and the access and refresh tokens minted under them. A client is the application's, whether it registered dynamically or is known by its metadata document, and stays. |
|
|
213
|
+
| `ledger` | erase | Balances in every currency, the transaction log, holds. |
|
|
214
|
+
| `rating` | erase | The rating in every pool, and the control-plane acts on it. The person's place in every logged outcome is anonymized instead, so each opponent's rating still replays exactly. |
|
|
215
|
+
| `leaderboard` | erase | Entries on every board, in every window, what each session result put on them, and their moderation history. |
|
|
216
|
+
| `matchmaking` | erase | Invites sent or received, friendships and requests on either side, and the person's place, undelivered match and drop records in every game's queue. A room code expires on its own TTL. |
|
|
217
|
+
| `multiplayer` | anonymize | Session results: the person's id in the players, scores and winner is replaced, so the other players' results stay. A session in flight they play in is closed with no result, and leaves the session index. |
|
|
218
|
+
| `support` | erase | Threads linked to the account, or sent from its address and linked to no other account, with messages, attachments, raw mail, classifications, read state, assignment history, and each message's vector in the semantic message index with its model stamp. On other people's threads, the handovers they made lose their id; who held a thread is an opaque reference and stays with it. |
|
|
219
|
+
| `testers` | erase | Cohort memberships under the account's address, and their events. Cohort counts stay. |
|
|
220
|
+
| `artifacts` | erase | Repositories the person owns, with their contents and grants, and the grants they hold. The record of every token minted for them is anonymized instead, so a token still listed reads as the kit's. |
|
|
221
|
+
| `media` | erase | Records the person holds as themselves, with their bytes and hashes. A record made for an organization is the organization's. |
|
|
222
|
+
| `storage` | erase | Files the person holds as themselves, with their bytes and share links. A file made for an organization is the organization's. |
|
|
223
|
+
| `organization` | erase | Memberships, the organization each session acted for, ownership offers made to or by them, invitations addressed to them. Invitations they sent and organizations' history keep their id; an organization they were the last owner of is left without one. |
|
|
224
|
+
| `payments` | retain | Purchases, entitlements, provider accounts, overrides, meter counters and usage reports of a user subject. *Kept for tax and accounting records, which the law requires a business to hold after an account is closed.* |
|
|
225
|
+
| `email` | retain | The address on the suppression list, and the log of mail sent to it. *Kept so your unsubscribe holds: the address stays on the list of addresses not to mail, with the record of what was sent to it.* |
|
|
226
|
+
| `audit` | retain | Every audit event where the person is the actor. *Kept as the record of who did what, which a security review or a dispute is read against.* |
|
|
227
|
+
| `controlplane` | retain | Every legal hold placed on the person, standing or released. *Kept as the record that a legal hold stood, when it was placed and why it ended.* The export says when each was placed and released, never who placed it or why. |
|
|
228
|
+
| `consent` | retain | Every grant and withdrawal, with the documents and evidence behind them and the visitors merged into the account. *Kept as the proof of what you agreed to and when you withdrew it, which the law asks us to be able to show.* |
|
|
229
|
+
|
|
230
|
+
`packages/cli/src/capabilities/personRows.test.ts` holds the kit to it. It constructs every capability package, walks its schema, and fails the build when a table names a person — `userId`, `ownerId`, `subjectId`, `actorId`, any `…UserId`, either side of an invite or a friendship, or an address — in a capability that declares no `user` contribution, or one without an export. `isPersonColumn` and `personRowGaps` in `@pithy-sh/core/src/capability/personColumns` are the rule, if you want to hold your own capabilities to it.
|
|
194
231
|
|
|
195
232
|
## The purge contribution
|
|
196
233
|
|
|
@@ -215,3 +252,18 @@ defineCapability({ name: "app", requiredBindings: [], purge: [purge] });
|
|
|
215
252
|
```
|
|
216
253
|
|
|
217
254
|
The purge runs every composed contribution as its own step, named for its capability, so a failure retries that capability alone. That is why there is at most one per subject per capability, and why `erase` must succeed when the rows are already gone: a step is retried after a failure that may have come once they were. Any fault in `erase` is retried with the platform's backoff, because the contract makes it safe to. `export` is optional; without one, the export lists the capability as `not_exported`. A throw from it costs its own entry, never the document. The kit knows two subjects, `user` and `organization` — the second for rows scoped to a tenant, which `@pithy-sh/organization`'s purge runs ([`organization-lifecycle.md`](../../organization/docs/organization-lifecycle.md#the-purge)) — and `defineCapability` refuses a contribution for any other. Declare one on your own `app` capability for your own tables.
|
|
255
|
+
|
|
256
|
+
**Or keep the rows, and say why.** Not every row about a person should go: a payment record is commonly kept for tax law, a suppression has to outlive the person or the unsubscribe stops holding, and an audit trail is the record of who acted. A contribution with `retain` is the third disposition beside erase and anonymize. It takes a basis, one sentence written for the person, and an `export`, which it may not leave out — rows that are kept are rows an access request is answered with — and no `erase`. `defineCapability` refuses one without a basis, without an export, or with an erase as well. The purge records the step as `purge_retained` and erases nothing; the export carries the rows, `disposition: "retain"` and the basis.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const kept: PurgeContribution = {
|
|
260
|
+
subject: "user",
|
|
261
|
+
summary: "Keeps the user's invoices.",
|
|
262
|
+
retain: { basis: "Kept for tax records." },
|
|
263
|
+
export: async ({ subject, env }) => ({ invoices: [] }),
|
|
264
|
+
};
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
**Rows found by address.** A step is handed `address`, a function that reads the account's address when called — `null` once it is gone. Call it inside `erase` or `export`; it is never carried in the Workflow's journal. Compare it in `normalizeAddress`'s form from `@pithy-sh/core/src/address/address`, the form the kit stores addresses in.
|
|
268
|
+
|
|
269
|
+
**Rows keyed by a column.** For tables whose rows name the person in a column and need nothing but reading out and deleting, `personRowsPurge` from `@pithy-sh/core/src/capability/personRows` writes the contribution: it exports every matching row decoded through its schema, and deletes them all in one batch. `personRowsExport` is its export alone, for a contribution that retains. A table's `omit` leaves columns out of the export, and its `redact` rewrites a row before that, for a credential only some rows hold — payments uses it to drop a Google Play purchase token from the columns a Play row keys on. `credentialFields` from `@pithy-sh/core/src/capability/purge` names every field in an export that holds a credential, so a test can assert there are none.
|
package/docs/apple-signin.md
CHANGED
|
@@ -82,11 +82,22 @@ Magic link and email OTP have no return URL — they work on any URL, preview or
|
|
|
82
82
|
|
|
83
83
|
## 6. Mobile
|
|
84
84
|
|
|
85
|
-
Native iOS uses Apple's own Sign in with Apple flow, not the web redirect. The app
|
|
85
|
+
Native iOS uses Apple's own Sign in with Apple flow, not the web redirect. The app asks Apple for an identity token with `expo-apple-authentication` and posts it to the Worker. The `appBundleIdentifier` is the audience that token is validated against, which is why it is part of the credential.
|
|
86
86
|
|
|
87
|
-
|
|
87
|
+
The route is Better Auth's social sign-in, with the token in the body instead of a redirect:
|
|
88
88
|
|
|
89
|
-
|
|
89
|
+
```http
|
|
90
|
+
POST /auth/sign-in/social
|
|
91
|
+
Content-Type: application/json
|
|
92
|
+
|
|
93
|
+
{ "provider": "apple", "idToken": { "token": "<identity token>", "nonce": "<raw nonce>" } }
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`nonce` is the raw value the app generated. Hand Apple its SHA-256 and send the raw one here; the Worker accepts either form. A token older than an hour is refused. The answer is `{ "token": "<session token>", "user": { … } }`, and `token` is the bearer credential: hand it to `session.adopt` from `@pithy-sh/auth/src/client/bearer`, which stores it in the Keychain and rotates it before it expires. `pithy ui add react-native` scaffolds the screen that does all of this. A refusal arrives in Better Auth's own shape, for example `{ "code": "INVALID_TOKEN" }` when the audience does not match `appBundleIdentifier`.
|
|
97
|
+
|
|
98
|
+
You do **not** register a deep-link or custom-scheme URL in the Apple portal. Apple only ever returns to the Services ID's return URL or, for native, hands the identity token straight to the app.
|
|
99
|
+
|
|
100
|
+
A provider without a native token flow signs in through the redirect instead, and comes back to the app on its own link. Use an https universal link (iOS) or app link (Android) when you can: the system opens it only in the app that proves it owns the domain, through `apple-app-site-association` or `assetlinks.json`. A custom scheme such as `myapp://` works too, but any installed app can claim one. Either must be in `trustedOrigins`, the https link by its origin and the scheme by prefix, or the Worker refuses the `callbackURL`:
|
|
90
101
|
|
|
91
102
|
```ts
|
|
92
103
|
auth({
|
|
@@ -94,6 +105,23 @@ auth({
|
|
|
94
105
|
});
|
|
95
106
|
```
|
|
96
107
|
|
|
108
|
+
Set the app's `universalLinkOrigin` and that origin must be in `trustedOrigins` too, beside the scheme. The scaffolded sign-in then returns on the https link, and an in-app auth session closes on an https callback only on iOS 17.4 or later. To support an older iOS, leave `universalLinkOrigin` unset and return on the custom scheme.
|
|
109
|
+
|
|
110
|
+
A cookie set on that redirect would land in the system browser, which the app never reads, so the Worker hands the session over with a one-time code instead:
|
|
111
|
+
|
|
112
|
+
1. Before the sign-in starts, the app makes a verifier with `createHandoffVerifier` from `@pithy-sh/auth/src/client/handoff`, passing `expo-crypto`'s `getRandomBytes` and `digest`. It keeps the verifier in memory.
|
|
113
|
+
2. It opens `nativeSignInStartURL({ origin, provider, callbackURL })` with `WebBrowser.openAuthSessionAsync`, where `callbackURL` is `handoffCallbackURL("https://app.example.com/auth/callback", challenge)`, or the custom-scheme link: the app's link with the verifier's S256 challenge on it as `handoff_challenge`. That is `GET /auth/sign-in/social/start`, which starts the sign-in inside the sign-in sheet and sends it on to the provider. Never post `/auth/sign-in/social` from the app for a redirect: Better Auth checks a signed `state` cookie at the provider's callback, and only the sheet's own jar can carry it there. The route refuses a navigation another page started (`Sec-Fetch-Site` other than `none`), so open it from the app, never from a link.
|
|
114
|
+
3. The sign-in returns to `https://app.example.com/auth/callback?code=<code>`. `handoffCode(link)` reads it, on any React Native runtime.
|
|
115
|
+
4. Within 60 seconds, the app calls `exchangeHandoff({ code, verifier }, session.options)`, which posts both to `POST /auth/handoff`. The answer is `{ "token", "expiresAt" }`. Hand `token` to `session.adopt`.
|
|
116
|
+
|
|
117
|
+
The code is good once. A spent, expired or unknown code, or a wrong verifier, gets `auth/handoff_invalid`, and any attempt spends the code: sign in again. So does a verifier outside RFC 7636's shape, 43 to 128 characters from `A-Z a-z 0-9 - . _ ~`; `createHandoffVerifier` always makes one inside it. Another app that claims the same scheme and catches the link has the code but not the verifier, so it has nothing to trade. A custom-scheme link with no challenge gets `?error=handoff_challenge_required` and no code.
|
|
118
|
+
|
|
119
|
+
A magic link on native needs a universal link. Whoever asks for a magic link chooses its challenge, and somebody else opens it, so an app that claims your custom scheme could ask for a link to your user's address and catch the code it hands back. The Worker hands a magic link off only to an https link in `trustedOrigins`; one to a custom scheme gets `?error=handoff_scheme_refused`, and no session is kept. Without a universal link, sign in by email with a one-time code instead.
|
|
120
|
+
|
|
121
|
+
The challenge is what asks for a code. An `https` callback that carries one is handed off like a custom scheme. An `https` callback without one is a web page to the Worker, so it gets a cookie, as a browser would, and no code.
|
|
122
|
+
|
|
123
|
+
The device id goes to the auth routes alone. It is listed to operators and recorded in the audit trail, so no other capability takes it as proof of anything. Consent knows a signed-out phone by a visitor id of its own, which the scaffolded app mints and keeps in the secure store.
|
|
124
|
+
|
|
97
125
|
## Where the credentials live
|
|
98
126
|
|
|
99
127
|
**All three values travel as one typed JSON secret.** The Services ID, the signed JWT, and the bundle id are stored together — through `@pithy-sh/secrets`, never committed, never an env literal — as `auth-apple-credentials`:
|
|
@@ -134,7 +162,7 @@ A sign-in attempt with Apple then answers `503` with the code `auth/provider_una
|
|
|
134
162
|
- [ ] Client secret JWT generated: ES256, `iss` = Team ID, `sub` = Services ID, `aud` = `https://appleid.apple.com`, `exp` ≤ 6 months.
|
|
135
163
|
- [ ] Return URL registered per environment as `<baseURL><basePath>/callback/apple`.
|
|
136
164
|
- [ ] Return URL host matches each environment's `baseURL`; domain verified and https.
|
|
137
|
-
- [ ]
|
|
165
|
+
- [ ] The app's universal link origin, or its custom scheme, listed in `trustedOrigins` (no deep link in the Apple portal).
|
|
138
166
|
- [ ] `clientId` + `clientSecret` + optional `appBundleIdentifier` stored together via `pithy secrets create auth-apple-credentials` (typed JSON); Apple enabled in config with `apple: { enabled: true }`.
|
|
139
167
|
- [ ] A plan to regenerate and rotate the client secret before it expires.
|
|
140
168
|
- [ ] `requireLocalEmailVerified` left on.
|
package/docs/facebook-oauth.md
CHANGED
|
@@ -46,7 +46,7 @@ Pithy requests the `email` scope. You do not configure scopes anywhere — Pithy
|
|
|
46
46
|
|
|
47
47
|
## 4. Mobile
|
|
48
48
|
|
|
49
|
-
You do not register a deep-link URI with Facebook. Facebook only ever redirects to the Worker's `/auth/callback/facebook`. The
|
|
49
|
+
You do not register a deep-link URI with Facebook. Facebook only ever redirects to the Worker's `/auth/callback/facebook`. The app opens `GET /auth/sign-in/social/start?provider=facebook&callbackURL=…` in the system browser's sign-in sheet, never posting `/auth/sign-in/social` itself. `callbackURL` is the app's own link, `myapp://auth/callback` or a universal link, carrying the S256 challenge of a verifier only the app holds as `handoff_challenge`. The Worker completes the exchange and returns to that link with a one-time `?code=`, which the app trades with the verifier at `POST /auth/handoff` for the session token. [`apple-signin.md`](apple-signin.md) §6 has the steps, and `pithy ui add react-native` scaffolds them. The link must be in `trustedOrigins`, the scheme by prefix and an https link by its origin:
|
|
50
50
|
|
|
51
51
|
```ts
|
|
52
52
|
auth({
|
|
@@ -89,5 +89,5 @@ A sign-in attempt with Facebook then answers `503` with the code `auth/provider_
|
|
|
89
89
|
- [ ] Meta app created with the Facebook Login product.
|
|
90
90
|
- [ ] Valid OAuth Redirect URI set to `<baseURL><basePath>/callback/facebook`, host matching each environment's `baseURL`.
|
|
91
91
|
- [ ] App ID and app secret in hand.
|
|
92
|
-
- [ ]
|
|
92
|
+
- [ ] The app's scheme, and its universal-link origin when it has one, listed in `trustedOrigins` (no deep link in Facebook).
|
|
93
93
|
- [ ] `clientId` + `clientSecret` stored together via `pithy secrets create auth-facebook-credentials` (typed JSON); Facebook enabled in config with `facebook: { enabled: true }`.
|
package/docs/github-oauth.md
CHANGED
|
@@ -52,7 +52,7 @@ Pithy requests `user:email`. That is what lets the sign-in read your primary ema
|
|
|
52
52
|
|
|
53
53
|
## 4. Mobile
|
|
54
54
|
|
|
55
|
-
You do not register a deep-link URI with GitHub. GitHub only ever redirects to the Worker's `/auth/callback/github`. The
|
|
55
|
+
You do not register a deep-link URI with GitHub. GitHub only ever redirects to the Worker's `/auth/callback/github`. The app opens `GET /auth/sign-in/social/start?provider=github&callbackURL=…` in the system browser's sign-in sheet, never posting `/auth/sign-in/social` itself. `callbackURL` is the app's own link, `myapp://auth/callback` or a universal link, carrying the S256 challenge of a verifier only the app holds as `handoff_challenge`. The Worker completes the exchange and returns to that link with a one-time `?code=`, which the app trades with the verifier at `POST /auth/handoff` for the session token. [`apple-signin.md`](apple-signin.md) §6 has the steps, and `pithy ui add react-native` scaffolds them. The link must be in `trustedOrigins`, the scheme by prefix and an https link by its origin:
|
|
56
56
|
|
|
57
57
|
```ts
|
|
58
58
|
auth({
|
|
@@ -149,7 +149,7 @@ A sign-in attempt with GitHub then answers `503` with the code `auth/provider_un
|
|
|
149
149
|
- [ ] GitHub OAuth app registered (one per environment).
|
|
150
150
|
- [ ] Authorization callback URL set to `<baseURL><basePath>/callback/github`, host matching each environment's `baseURL`.
|
|
151
151
|
- [ ] Client ID and a generated client secret in hand.
|
|
152
|
-
- [ ]
|
|
152
|
+
- [ ] The app's scheme, and its universal-link origin when it has one, listed in `trustedOrigins` (no deep link in GitHub).
|
|
153
153
|
- [ ] `clientId` + `clientSecret` stored together via `pithy secrets create auth-github-credentials` (typed JSON); GitHub enabled in config with `github: { enabled: true }`.
|
|
154
154
|
- [ ] GitHub primary email verified on GitHub (or plan for the magic-link verify-to-link step).
|
|
155
155
|
- [ ] Decided whether GitHub may create accounts — `github: { allowSignUp: false }` if it may not.
|
package/docs/google-oauth.md
CHANGED
|
@@ -62,7 +62,7 @@ Magic link and email OTP have no redirect URI — they work on any URL, preview
|
|
|
62
62
|
|
|
63
63
|
You do **not** register a custom-scheme or deep-link URI in Google Console. Google only ever redirects to the Worker's `/auth/callback/google`. The Worker, not Google, is what hands control back to the app.
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
A redirect sign-in starts in the system browser's sign-in sheet, not in the app. The app opens `GET /auth/sign-in/social/start?provider=google&callbackURL=…`, where `callbackURL` is its own link, `myapp://auth/callback` or a universal link, carrying the S256 challenge of a verifier only the app holds as `handoff_challenge`. The Worker completes the OAuth exchange and returns to that link with a one-time `?code=`, never a cookie. The app trades the code and the verifier at `POST /auth/handoff` for the session token. The link must be in `trustedOrigins`, the scheme by prefix and an https link by its origin:
|
|
66
66
|
|
|
67
67
|
```ts
|
|
68
68
|
auth({
|
|
@@ -70,14 +70,16 @@ auth({
|
|
|
70
70
|
});
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
[`apple-signin.md`](apple-signin.md) §6 has the handoff step by step, with the helpers from `@pithy-sh/auth/src/client/handoff`. `pithy ui add react-native` scaffolds a sign-in that does all of it.
|
|
74
|
+
|
|
75
|
+
**Native Google sign-in skips the redirect.** On a phone the scaffolded sign-in uses Google's SDK and posts the id token it gets to `POST /auth/sign-in/social`. The SDK asks for that token with the **web** client id as its audience, which is the one the Worker checks, so the credential stays the one web client above. Register an **iOS** and an **Android** OAuth client in Google Console too, which the SDK needs on each platform, then put the public ids in the app's `src/pithy-config.generated.ts`:
|
|
74
76
|
|
|
75
77
|
```ts
|
|
76
|
-
|
|
77
|
-
google: { clientId: ["<web-id>", "<ios-id>", "<android-id>"] },
|
|
78
|
-
});
|
|
78
|
+
google: { webClientId: "<web-id>", iosClientId: "<ios-id>" },
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
`webClientId` null turns native Google sign-in off, and the app signs in with Google through the redirect instead. `iosClientId` is null on an Android-only app.
|
|
82
|
+
|
|
81
83
|
## Where the credentials live
|
|
82
84
|
|
|
83
85
|
**Both credentials travel as one typed JSON secret.** The client id and client secret are stored together — through `@pithy-sh/secrets`, never committed, never an env literal — as `auth-google-credentials`:
|
|
@@ -113,7 +115,7 @@ A sign-in attempt with Google then answers `503` with the code `auth/provider_un
|
|
|
113
115
|
- [ ] Web OAuth client created; client ID and secret in hand.
|
|
114
116
|
- [ ] Redirect URI registered per environment, each as `<baseURL><basePath>/callback/google`.
|
|
115
117
|
- [ ] Redirect host matches each environment's `baseURL`.
|
|
116
|
-
- [ ]
|
|
117
|
-
- [ ] Native
|
|
118
|
+
- [ ] The app's scheme, and its universal-link origin when it has one, listed in `trustedOrigins` (no deep link in Google Console).
|
|
119
|
+
- [ ] Native Google sign-in: iOS and Android OAuth clients registered; `google.webClientId` and `google.iosClientId` set in the app's `src/pithy-config.generated.ts`.
|
|
118
120
|
- [ ] `clientId` + `clientSecret` stored together via `pithy secrets create auth-google-credentials` (typed JSON); Google enabled in config with `google: { enabled: true }`.
|
|
119
121
|
- [ ] `requireLocalEmailVerified` left on.
|
package/docs/microsoft-oauth.md
CHANGED
|
@@ -100,7 +100,7 @@ A directory user with no `mail` attribute arrives with no email at all. That sig
|
|
|
100
100
|
|
|
101
101
|
## 7. Mobile
|
|
102
102
|
|
|
103
|
-
You do not register a deep-link URI with Microsoft. Microsoft only ever redirects to the Worker's `/auth/callback/microsoft`. The
|
|
103
|
+
You do not register a deep-link URI with Microsoft. Microsoft only ever redirects to the Worker's `/auth/callback/microsoft`. The app opens `GET /auth/sign-in/social/start?provider=microsoft&callbackURL=…` in the system browser's sign-in sheet, never posting `/auth/sign-in/social` itself. `callbackURL` is the app's own link, `myapp://auth/callback` or a universal link, carrying the S256 challenge of a verifier only the app holds as `handoff_challenge`. The Worker completes the exchange and returns to that link with a one-time `?code=`, which the app trades with the verifier at `POST /auth/handoff` for the session token. [`apple-signin.md`](apple-signin.md) §6 has the steps, and `pithy ui add react-native` scaffolds them. The link must be in `trustedOrigins`, the scheme by prefix and an https link by its origin:
|
|
104
104
|
|
|
105
105
|
```ts
|
|
106
106
|
auth({
|
|
@@ -165,7 +165,7 @@ A sign-in attempt with Microsoft then answers `503` with the code `auth/provider
|
|
|
165
165
|
- [ ] Redirect URI `<baseURL><basePath>/callback/microsoft` registered for each environment, platform **Web**.
|
|
166
166
|
- [ ] Client secret created, its **Value** copied, and its expiry on somebody's calendar.
|
|
167
167
|
- [ ] `xms_edov` added to the ID token under **Token configuration** — or the magic-link step accepted for every work and school address.
|
|
168
|
-
- [ ]
|
|
168
|
+
- [ ] The app's scheme, and its universal-link origin when it has one, listed in `trustedOrigins` (no deep link in Microsoft).
|
|
169
169
|
- [ ] `clientId` + `clientSecret` + `tenantId` stored together via `pithy secrets create auth-microsoft-credentials` (typed JSON); Microsoft enabled in config with `microsoft: { enabled: true }`.
|
|
170
170
|
- [ ] Decided whether Microsoft may create accounts — `microsoft: { allowSignUp: false }` if it may not.
|
|
171
171
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithy-sh/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"dist",
|
|
12
12
|
"src",
|
|
13
13
|
"pithy.manifest.json",
|
|
14
|
+
"pithy.mcp.manifest.json",
|
|
14
15
|
"docs",
|
|
15
16
|
"!src/**/*.test.*",
|
|
16
17
|
"!dist/**/*.test.*"
|
|
@@ -36,22 +37,27 @@
|
|
|
36
37
|
"reset": "bun run clean && rm -rf node_modules"
|
|
37
38
|
},
|
|
38
39
|
"dependencies": {
|
|
40
|
+
"@better-auth/cimd": "^1.7.11",
|
|
41
|
+
"@better-auth/core": "^1.7.11",
|
|
39
42
|
"@better-auth/i18n": "^1.7.11",
|
|
43
|
+
"@better-auth/oauth-provider": "^1.7.11",
|
|
40
44
|
"@cloudflare/workers-types": "^5.20260729.1",
|
|
41
45
|
"@hono/zod-validator": "^0.9.0",
|
|
42
46
|
"better-auth": "^1.7.11"
|
|
43
47
|
},
|
|
44
48
|
"peerDependencies": {
|
|
45
|
-
"@pithy-sh/core": "^0.
|
|
46
|
-
"@pithy-sh/email": "^0.
|
|
47
|
-
"@pithy-sh/secrets": "^0.6.
|
|
48
|
-
"@pithy-sh/turnstile": "^0.
|
|
49
|
+
"@pithy-sh/core": "^0.15.0",
|
|
50
|
+
"@pithy-sh/email": "^0.8.1",
|
|
51
|
+
"@pithy-sh/secrets": "^0.6.3",
|
|
52
|
+
"@pithy-sh/turnstile": "^0.7.1",
|
|
49
53
|
"hono": "^4.13.2",
|
|
50
54
|
"kysely": "^0.29.0",
|
|
51
55
|
"zod": "^4.4.0"
|
|
52
56
|
},
|
|
53
57
|
"devDependencies": {
|
|
58
|
+
"@better-auth/api-key": "1.7.11",
|
|
54
59
|
"@cloudflare/vitest-plugin": "^1.4.2",
|
|
60
|
+
"@pithy-sh/artifacts": "workspace:*",
|
|
55
61
|
"@pithy-sh/cloudflare": "workspace:*",
|
|
56
62
|
"@pithy-sh/core": "workspace:*",
|
|
57
63
|
"@pithy-sh/email": "workspace:*",
|
package/pithy.manifest.json
CHANGED
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
],
|
|
90
|
-
"whenToEnable": "Sign-in for your app — passwordless, mobile and web both first-class. Magic link, email OTP, and social sign-in with Google, Apple, Facebook, GitHub, and Microsoft. A successful sign-in mints a
|
|
90
|
+
"whenToEnable": "Sign-in for your app — passwordless, mobile and web both first-class. Magic link, email OTP, and social sign-in with Google, Apple, Facebook, GitHub, and Microsoft. A successful sign-in mints a rotated session whose token is the bearer credential, and short-lived JWTs that services outside the Worker verify against `/jwks`. It fills core's identity seams, so every other capability just calls `requireAuth()`. This is the keystone capability; add it first.",
|
|
91
91
|
"scaffold": [
|
|
92
92
|
"Create the session signing secret: `pithy secrets create auth-session-secret`.",
|
|
93
93
|
"Add the `AUTH_RATE_LIMITER` Workers Rate Limiting binding to each wrangler.jsonc env — the coarse per-IP edge guard on the auth routes. For example: `\"ratelimits\": [{ \"name\": \"AUTH_RATE_LIMITER\", \"namespace_id\": \"1001\", \"simple\": { \"limit\": 60, \"period\": 60 } }]`. This is tier 1; Better Auth's per-action limiter (tier 2) is built in.",
|
|
@@ -99,7 +99,7 @@
|
|
|
99
99
|
"Facebook (optional): set `facebook: { enabled: true }`, then `pithy secrets create auth-facebook-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/facebook-oauth.md.",
|
|
100
100
|
"GitHub (optional): set `github: { enabled: true }`, then `pithy secrets create auth-github-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/github-oauth.md.",
|
|
101
101
|
"Microsoft (optional): set `microsoft: { enabled: true }`, then `pithy secrets create auth-microsoft-credentials` with the typed JSON `{ clientId, clientSecret, tenantId }`. Add the `xms_edov` optional claim to the ID token in the app registration, or every work and school address is verified by magic link before it links. See the package's docs/microsoft-oauth.md.",
|
|
102
|
-
"Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend` to suspend somebody and reinstate them, `auth:users:delete`, `auth:users:export
|
|
102
|
+
"Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend` to suspend somebody and reinstate them, `auth:users:delete`, `auth:users:export`; and `auth:verifications:read` for the ledger of every sign-in link and code sent, used or expired, and the mail that carried it. Nine scopes and not one admin flag — a support tool that looks people up must not also be able to sign the customer base out, and an incident-response tool that kills a session has no business reading every address in the user table. With the seam not composed every /auth/admin route answers `controlplane/not_connected`, and no app session opens any of them whatever it carries. There is deliberately no impersonation: signing in as a user produces a credential indistinguishable from theirs, so it is excluded until it has its own design and security review."
|
|
103
103
|
],
|
|
104
104
|
"configOptions": [
|
|
105
105
|
{
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mcp",
|
|
3
|
+
"package": "@pithy-sh/auth",
|
|
4
|
+
"requiredBindings": [{ "type": "d1", "name": "DB" }],
|
|
5
|
+
"peerCapabilities": ["auth"],
|
|
6
|
+
"optionalCapabilities": ["audit"],
|
|
7
|
+
"migrationNamespace": "mcp",
|
|
8
|
+
"scaffold": [
|
|
9
|
+
"Choose who may connect an agent at all: `pithy add mcp --floor signed-in`, `--floor power:<name>` or `--floor entitlement:<name>`. There is no default. `pithy doctor` prints the floor in force.",
|
|
10
|
+
"Run `pithy ui add` for the two screens an agent's user needs: `agent-consent.tsx`, where they sign in and approve, and `connected-applications.tsx`, where they see and revoke what they approved.",
|
|
11
|
+
"Make a route a tool with `describeRoute({ operation, tool })`: `tool: true` on a `GET`, `tool: { effect }` on anything else, with the effect one of `writes`, `sends`, `charges` or `deletes`. A route that declares no `tool` is never offered.",
|
|
12
|
+
"Run `pithy migrate` to create the `pithy_mcp_*` tables beside auth's."
|
|
13
|
+
],
|
|
14
|
+
"configOptions": [
|
|
15
|
+
{
|
|
16
|
+
"key": "path",
|
|
17
|
+
"default": "/mcp",
|
|
18
|
+
"describe": "Where the MCP endpoint mounts. An agent is pointed at <origin><path>."
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"key": "floor",
|
|
22
|
+
"describe": "Who may connect an agent at all: \"signed-in\", { power } or { entitlement }. Every tool is still gated by its own route."
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"key": "consentPath",
|
|
26
|
+
"default": "/agent-consent",
|
|
27
|
+
"describe": "The consent screen's path in this Worker's front end. pithy ui add writes it there."
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"key": "database",
|
|
31
|
+
"default": "DB",
|
|
32
|
+
"describe": "The D1 binding auth uses. The provider's tables live beside auth's."
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"whenToEnable": "Let your users' agents use your app as them. Composing it mounts an MCP endpoint at /mcp and an OAuth 2.1 authorization server in auth: an agent registers itself, its user signs in and approves on your own consent screen, and it gets a token bound to this endpoint and to that user. Every tool is a route that opted in with describeRoute, and each call runs through that route's own gates, so an agent can do what its user can and nothing more. Off until composed, and composing it means choosing a floor: every signed-in user, a power, or an entitlement. Needs auth."
|
|
36
|
+
}
|