@pithy-sh/auth 0.15.3 → 0.17.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 +4 -0
- package/dist/attestation/appAttest/assertion.d.ts +32 -0
- package/dist/attestation/appAttest/assertion.d.ts.map +1 -0
- package/dist/attestation/appAttest/assertion.js +59 -0
- package/dist/attestation/appAttest/attestation.d.ts +49 -0
- package/dist/attestation/appAttest/attestation.d.ts.map +1 -0
- package/dist/attestation/appAttest/attestation.js +111 -0
- package/dist/attestation/appAttest/authData.d.ts +24 -0
- package/dist/attestation/appAttest/authData.d.ts.map +1 -0
- package/dist/attestation/appAttest/authData.js +32 -0
- package/dist/attestation/appAttest/base64.d.ts +8 -0
- package/dist/attestation/appAttest/base64.d.ts.map +1 -0
- package/dist/attestation/appAttest/base64.js +27 -0
- package/dist/attestation/appAttest/bytes.d.ts +7 -0
- package/dist/attestation/appAttest/bytes.d.ts.map +1 -0
- package/dist/attestation/appAttest/bytes.js +19 -0
- package/dist/attestation/appAttest/cbor.d.ts +20 -0
- package/dist/attestation/appAttest/cbor.d.ts.map +1 -0
- package/dist/attestation/appAttest/cbor.js +96 -0
- package/dist/attestation/appAttest/der.d.ts +38 -0
- package/dist/attestation/appAttest/der.d.ts.map +1 -0
- package/dist/attestation/appAttest/der.js +106 -0
- package/dist/attestation/appAttest/keys.d.ts +15 -0
- package/dist/attestation/appAttest/keys.d.ts.map +1 -0
- package/dist/attestation/appAttest/keys.js +37 -0
- package/dist/attestation/appAttest/root.d.ts +9 -0
- package/dist/attestation/appAttest/root.d.ts.map +1 -0
- package/dist/attestation/appAttest/root.js +12 -0
- package/dist/attestation/appAttest/verifier.d.ts +39 -0
- package/dist/attestation/appAttest/verifier.d.ts.map +1 -0
- package/dist/attestation/appAttest/verifier.js +121 -0
- package/dist/attestation/appAttest/x509.d.ts +50 -0
- package/dist/attestation/appAttest/x509.d.ts.map +1 -0
- package/dist/attestation/appAttest/x509.js +163 -0
- package/dist/attestation/challenge.d.ts +26 -0
- package/dist/attestation/challenge.d.ts.map +1 -0
- package/dist/attestation/challenge.js +47 -0
- package/dist/attestation/config.d.ts +72 -0
- package/dist/attestation/config.d.ts.map +1 -0
- package/dist/attestation/config.js +52 -0
- package/dist/attestation/errors.d.ts +30 -0
- package/dist/attestation/errors.d.ts.map +1 -0
- package/dist/attestation/errors.js +45 -0
- package/dist/attestation/gate.d.ts +27 -0
- package/dist/attestation/gate.d.ts.map +1 -0
- package/dist/attestation/gate.js +78 -0
- package/dist/attestation/playIntegrity/google.d.ts +47 -0
- package/dist/attestation/playIntegrity/google.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/google.js +178 -0
- package/dist/attestation/playIntegrity/verdict.d.ts +40 -0
- package/dist/attestation/playIntegrity/verdict.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/verdict.js +93 -0
- package/dist/attestation/playIntegrity/verifier.d.ts +22 -0
- package/dist/attestation/playIntegrity/verifier.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/verifier.js +64 -0
- package/dist/attestation/verifier.d.ts +60 -0
- package/dist/attestation/verifier.d.ts.map +1 -0
- package/dist/attestation/verifier.js +46 -0
- package/dist/attestation/wire.d.ts +42 -0
- package/dist/attestation/wire.d.ts.map +1 -0
- package/dist/attestation/wire.js +72 -0
- package/dist/capability.d.ts +49 -6
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +42 -7
- package/dist/client/api.d.ts +37 -24
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +52 -41
- package/dist/client/attestation.d.ts +148 -0
- package/dist/client/attestation.d.ts.map +1 -0
- package/dist/client/attestation.js +321 -0
- package/dist/client/projection.d.ts +29 -4
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/appAttestKey.d.ts +30 -0
- package/dist/data/appAttestKey.d.ts.map +1 -0
- package/dist/data/appAttestKey.js +25 -0
- package/dist/data/attestationChallenge.d.ts +17 -0
- package/dist/data/attestationChallenge.d.ts.map +1 -0
- package/dist/data/attestationChallenge.js +19 -0
- package/dist/data/tables.d.ts +19 -1
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +6 -2
- package/dist/data/userLifecycle.d.ts +1 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +3 -2
- package/dist/hooks/runtime.d.ts +32 -0
- package/dist/hooks/runtime.d.ts.map +1 -0
- package/dist/hooks/runtime.js +25 -0
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +4 -2
- package/dist/http/devLoginRoute.js +3 -3
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +3 -2
- package/dist/http/responses.d.ts +15 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +13 -2
- package/dist/http/routes.d.ts +5 -1
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +92 -25
- package/dist/http/schemas.d.ts +7 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +7 -1
- package/dist/index.js +1 -1
- package/dist/instance/secrets.d.ts +86 -7
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +54 -8
- package/dist/lifecycle/erasure.d.ts.map +1 -1
- package/dist/lifecycle/erasure.js +2 -1
- package/dist/lifecycle/hooks.d.ts +18 -10
- package/dist/lifecycle/hooks.d.ts.map +1 -1
- package/dist/lifecycle/request.d.ts +2 -1
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +4 -1
- package/dist/lifecycle/transitions.d.ts +24 -16
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +27 -16
- package/dist/migrations/0009_attestation_challenges.d.ts +9 -0
- package/dist/migrations/0009_attestation_challenges.d.ts.map +1 -0
- package/dist/migrations/0009_attestation_challenges.js +21 -0
- package/dist/migrations/0010_app_attest_keys.d.ts +9 -0
- package/dist/migrations/0010_app_attest_keys.d.ts.map +1 -0
- package/dist/migrations/0010_app_attest_keys.js +17 -0
- package/dist/migrations/0011_retained_basis_key.d.ts +10 -0
- package/dist/migrations/0011_retained_basis_key.d.ts.map +1 -0
- package/dist/migrations/0011_retained_basis_key.js +18 -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/purge/run.d.ts +11 -11
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +9 -8
- package/dist/purge/workflow.d.ts +7 -1
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.js +6 -2
- package/dist/seeds/devSession.js +1 -1
- package/dist/test-utils/appAttestDevice.d.ts +92 -0
- package/dist/test-utils/appAttestDevice.d.ts.map +1 -0
- package/dist/test-utils/appAttestDevice.js +282 -0
- package/dist/test-utils/appAttestSample.d.ts +22 -0
- package/dist/test-utils/appAttestSample.d.ts.map +1 -0
- package/dist/test-utils/appAttestSample.js +24 -0
- package/dist/test-utils/googlePlay.d.ts +47 -0
- package/dist/test-utils/googlePlay.d.ts.map +1 -0
- package/dist/test-utils/googlePlay.js +117 -0
- package/dist/test-utils/liveApp.d.ts +76 -36
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +16 -5
- package/dist/test-utils/rollbackThrough.d.ts +11 -0
- package/dist/test-utils/rollbackThrough.d.ts.map +1 -0
- package/dist/test-utils/rollbackThrough.js +16 -0
- package/dist/test-utils/scopedBackend.d.ts +25 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +1 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +46 -10
- package/docs/attestation.md +173 -0
- package/package.json +5 -5
- package/pithy.manifest.json +14 -0
- package/src/attestation/appAttest/assertion.ts +65 -0
- package/src/attestation/appAttest/attestation.ts +159 -0
- package/src/attestation/appAttest/authData.ts +45 -0
- package/src/attestation/appAttest/base64.ts +29 -0
- package/src/attestation/appAttest/bytes.ts +18 -0
- package/src/attestation/appAttest/cbor.ts +116 -0
- package/src/attestation/appAttest/der.ts +126 -0
- package/src/attestation/appAttest/keys.ts +57 -0
- package/src/attestation/appAttest/root.ts +13 -0
- package/src/attestation/appAttest/verifier.ts +113 -0
- package/src/attestation/appAttest/x509.ts +209 -0
- package/src/attestation/challenge.ts +56 -0
- package/src/attestation/config.ts +118 -0
- package/src/attestation/errors.ts +60 -0
- package/src/attestation/gate.ts +105 -0
- package/src/attestation/playIntegrity/google.ts +239 -0
- package/src/attestation/playIntegrity/verdict.ts +149 -0
- package/src/attestation/playIntegrity/verifier.ts +77 -0
- package/src/attestation/verifier.ts +87 -0
- package/src/attestation/wire.ts +79 -0
- package/src/capability.ts +85 -16
- package/src/client/api.ts +73 -40
- package/src/client/attestation.ts +404 -0
- package/src/client/projection.ts +29 -4
- package/src/data/appAttestKey.ts +45 -0
- package/src/data/attestationChallenge.ts +23 -0
- package/src/data/tables.ts +5 -1
- package/src/data/userLifecycle.ts +9 -2
- package/src/hooks/runtime.ts +41 -0
- package/src/http/adminRoutes.ts +14 -7
- package/src/http/resolve.ts +8 -4
- package/src/http/responses.ts +29 -1
- package/src/http/routes.ts +128 -38
- package/src/http/schemas.ts +24 -0
- package/src/instance/secrets.ts +88 -9
- package/src/lifecycle/erasure.ts +2 -1
- package/src/lifecycle/hooks.ts +22 -10
- package/src/lifecycle/request.ts +4 -1
- package/src/lifecycle/transitions.ts +47 -28
- package/src/migrations/0009_attestation_challenges.ts +28 -0
- package/src/migrations/0010_app_attest_keys.ts +27 -0
- package/src/migrations/0011_retained_basis_key.ts +19 -0
- package/src/migrations/set.ts +7 -1
- package/src/purge/run.ts +29 -17
- package/src/purge/workflow.ts +7 -3
- package/src/test-utils/appAttestDevice.ts +399 -0
- package/src/test-utils/appAttestSample.ts +20 -0
- package/src/test-utils/googlePlay.ts +144 -0
- package/src/test-utils/liveApp.ts +31 -5
- package/src/test-utils/rollbackThrough.ts +24 -0
- package/src/version.generated.ts +1 -1
package/src/client/projection.ts
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
*
|
|
18
18
|
* **This is the only statement of the shape.** `@pithy-sh/ui-react`'s `templates/client-env.d.ts` — the
|
|
19
19
|
* ambient declaration `pithy ui add react` copies into an adopter's Worker — is generated from this type
|
|
20
|
-
* by `@pithy-sh/vite`'s `clientEnvDeclaration.ts
|
|
20
|
+
* by `@pithy-sh/vite`'s `clientEnvDeclaration.ts`. The unions and the per-field doc comments below
|
|
21
21
|
* are emitted verbatim, so what is written here is what a screen author reads.
|
|
22
22
|
*/
|
|
23
23
|
export type AuthClientProjection =
|
|
@@ -55,9 +55,8 @@ export type AuthClientProjection =
|
|
|
55
55
|
*
|
|
56
56
|
* **A second fact from {@link signUpEnabled}, and the screen needs both.** That one answers for
|
|
57
57
|
* magic link and OTP; this answers per provider. A project can let email create accounts while
|
|
58
|
-
* GitHub only signs existing ones in
|
|
59
|
-
*
|
|
60
|
-
* refuse (#559).
|
|
58
|
+
* GitHub only signs existing ones in, and with only the global flag a screen would promise an
|
|
59
|
+
* account directly beneath a button that will refuse.
|
|
61
60
|
*
|
|
62
61
|
* Optional, so a screen copied before this landed keeps compiling and reads `undefined` as "no
|
|
63
62
|
* provider objects" — the state every project was in until now.
|
|
@@ -78,4 +77,30 @@ export type AuthClientProjection =
|
|
|
78
77
|
otpLength: number;
|
|
79
78
|
/** Whether signing in may provision a new user. Drives the sign-up copy. */
|
|
80
79
|
signUpEnabled: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Native app attestation in this environment, when it has an attestation block. Absent, the send routes
|
|
82
|
+
* take no attestation, and a native app passes the humanity check as a web page does.
|
|
83
|
+
*
|
|
84
|
+
* Optional, so a screen copied before it existed keeps compiling.
|
|
85
|
+
*/
|
|
86
|
+
attestation?: {
|
|
87
|
+
/**
|
|
88
|
+
* `test` where the Worker accepts the documented test assertion, so a simulator, an emulator or CI sends
|
|
89
|
+
* it; `enforce` where only a real App Attest or Play Integrity assertion passes.
|
|
90
|
+
*/
|
|
91
|
+
mode: "enforce" | "test";
|
|
92
|
+
/**
|
|
93
|
+
* Whether a phone on each platform can pass by attesting here. Under `enforce`, `false` where the block
|
|
94
|
+
* allows no app for that platform or the Worker has no verifier for it, so that platform's phones pass the
|
|
95
|
+
* humanity check.
|
|
96
|
+
*
|
|
97
|
+
* Optional, so a screen copied before it existed keeps compiling; absent reads as both `true`.
|
|
98
|
+
*/
|
|
99
|
+
platforms?: {
|
|
100
|
+
/** Whether an iPhone can pass with App Attest, or the test assertion. */
|
|
101
|
+
ios: boolean;
|
|
102
|
+
/** Whether an Android phone can pass with Play Integrity, or the test assertion. */
|
|
103
|
+
android: boolean;
|
|
104
|
+
};
|
|
105
|
+
};
|
|
81
106
|
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/** The App Attest environment a key was attested in, as its AAGUID names it. */
|
|
8
|
+
export const AppAttestEnvironment = z
|
|
9
|
+
.enum(["production", "development"])
|
|
10
|
+
.describe(
|
|
11
|
+
"The App Attest environment a key was attested in: `production` for TestFlight and App Store builds, `development` for a build carrying the development App Attest entitlement.",
|
|
12
|
+
);
|
|
13
|
+
export type AppAttestEnvironment = z.output<typeof AppAttestEnvironment>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `pithy_auth_app_attest_keys`: an App Attest key an iOS app registered with an attestation Apple signed.
|
|
17
|
+
*
|
|
18
|
+
* One row per key, written once by the key route and then only its counter and last use, by each assertion that
|
|
19
|
+
* verifies (`../attestation/appAttest/keys.ts`). A key belongs to one install of the app, not to a person: it is
|
|
20
|
+
* registered before anybody signs in, and names no user.
|
|
21
|
+
*/
|
|
22
|
+
export const AppAttestKey = z
|
|
23
|
+
.object({
|
|
24
|
+
id: z
|
|
25
|
+
.string()
|
|
26
|
+
.describe("Primary key: the App Attest key id, unpadded base64url of its 32 bytes, SHA-256 of `publicKey`."),
|
|
27
|
+
publicKey: z
|
|
28
|
+
.string()
|
|
29
|
+
.describe(
|
|
30
|
+
"The key's P-256 public key, an X9.62 uncompressed point, unpadded base64url. Assertions verify with it.",
|
|
31
|
+
),
|
|
32
|
+
appId: z.string().describe("The App ID the key was attested for: `<TeamID>.<bundleId>`."),
|
|
33
|
+
environment: AppAttestEnvironment,
|
|
34
|
+
counter: z
|
|
35
|
+
.number()
|
|
36
|
+
.int()
|
|
37
|
+
.nonnegative()
|
|
38
|
+
.describe("The counter of the last assertion accepted, 0 at registration. Each assertion must exceed it."),
|
|
39
|
+
createdAt: SQLiteDate.describe("When the key was registered. Ms-epoch in SQLite."),
|
|
40
|
+
lastUsedAt: SQLiteDate.nullable().describe(
|
|
41
|
+
"When an assertion by this key last verified, or null before the first. Ms-epoch in SQLite.",
|
|
42
|
+
),
|
|
43
|
+
})
|
|
44
|
+
.describe("A registered App Attest key in `pithy_auth_app_attest_keys`.");
|
|
45
|
+
export type AppAttestKey = z.output<typeof AppAttestKey>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `pithy_auth_attestation_challenges`: a challenge the challenge route issued and nobody has presented yet.
|
|
9
|
+
*
|
|
10
|
+
* Keyed by the challenge's SHA-256, so a read of the table hands nobody a usable challenge. A row is deleted
|
|
11
|
+
* when its challenge is presented, pass or fail, which is what makes a challenge single-use, and issuing deletes
|
|
12
|
+
* the rows that ran out unpresented (`../attestation/challenge.ts`). It names no person and no device.
|
|
13
|
+
*/
|
|
14
|
+
export const AttestationChallenge = z
|
|
15
|
+
.object({
|
|
16
|
+
id: z
|
|
17
|
+
.string()
|
|
18
|
+
.describe("Primary key: the unpadded base64url SHA-256 of the challenge. The challenge itself is never stored."),
|
|
19
|
+
issuedAt: SQLiteDate.describe("When the challenge was issued. Ms-epoch in SQLite."),
|
|
20
|
+
expiresAt: SQLiteDate.describe("When the challenge stops being accepted. Ms-epoch in SQLite. Indexed."),
|
|
21
|
+
})
|
|
22
|
+
.describe("An issued, unpresented attestation challenge in `pithy_auth_attestation_challenges`.");
|
|
23
|
+
export type AttestationChallenge = z.output<typeof AttestationChallenge>;
|
package/src/data/tables.ts
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
5
|
import { createDatabase, type DatabaseSchema } from "@pithy-sh/core/src/data/db";
|
|
6
6
|
import type { Kysely } from "kysely";
|
|
7
|
+
import { AppAttestKey } from "./appAttestKey";
|
|
8
|
+
import { AttestationChallenge } from "./attestationChallenge";
|
|
7
9
|
import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth";
|
|
8
10
|
import { Device } from "./device";
|
|
9
11
|
import { RotatedToken } from "./rotatedToken";
|
|
@@ -16,7 +18,7 @@ import { VerificationOutcome } from "./verificationOutcome";
|
|
|
16
18
|
* (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
|
|
17
19
|
*
|
|
18
20
|
* The first six tables are Better-Auth-managed; `pithyAuthDevices`, `pithyAuthRotatedTokens`,
|
|
19
|
-
* `pithyAuthUserLifecycle` and `
|
|
21
|
+
* `pithyAuthUserLifecycle`, `pithyAuthVerificationOutcomes`, `pithyAuthAttestationChallenges` and `pithyAuthAppAttestKeys` are ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
|
|
20
22
|
* own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
|
|
21
23
|
*/
|
|
22
24
|
export const authTables = {
|
|
@@ -30,6 +32,8 @@ export const authTables = {
|
|
|
30
32
|
pithyAuthRotatedTokens: RotatedToken,
|
|
31
33
|
pithyAuthUserLifecycle: UserLifecycleEvent,
|
|
32
34
|
pithyAuthVerificationOutcomes: VerificationOutcome,
|
|
35
|
+
pithyAuthAttestationChallenges: AttestationChallenge,
|
|
36
|
+
pithyAuthAppAttestKeys: AppAttestKey,
|
|
33
37
|
};
|
|
34
38
|
export type AuthTables = typeof authTables;
|
|
35
39
|
|
|
@@ -33,7 +33,7 @@ export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
|
|
|
33
33
|
export const UserLifecycleActorType = z
|
|
34
34
|
.enum(["control-plane", "user", "system"])
|
|
35
35
|
.describe(
|
|
36
|
-
"Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder
|
|
36
|
+
"Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (a signed-in person: the account's own holder deleting it, or an organization's owner whose deletion of that organization reached it through the sole-member cascade), or `system` (the scheduled purge, with nobody calling).",
|
|
37
37
|
);
|
|
38
38
|
export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
|
|
39
39
|
|
|
@@ -55,7 +55,7 @@ export const UserLifecycleEvent = z
|
|
|
55
55
|
.string()
|
|
56
56
|
.nullable()
|
|
57
57
|
.describe(
|
|
58
|
-
"The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none.",
|
|
58
|
+
"The acting principal's id — the user's own id for a self-service deletion, the deleting owner's for an organization's cascade, the connection's for a management client. Null for `system`, and for a management client that named none.",
|
|
59
59
|
),
|
|
60
60
|
reason: z
|
|
61
61
|
.string()
|
|
@@ -87,6 +87,13 @@ export const UserLifecycleEvent = z
|
|
|
87
87
|
.describe(
|
|
88
88
|
"For a `deleted` row, when its purge comes due — kept here because the purge erases the account's own column. Null for every other row, and before `0007_erasure_record` (#823). Ms-epoch in SQLite.",
|
|
89
89
|
),
|
|
90
|
+
basisKey: z
|
|
91
|
+
.string()
|
|
92
|
+
.nullable()
|
|
93
|
+
.default(null)
|
|
94
|
+
.describe(
|
|
95
|
+
"For a `purge_retained` row, the catalog key its basis in `reason` translates through, under the retaining capability's own domain — `payments/purge.retained`. Null for every other row, for a retained step that names no key, and before `0011_retained_basis_key`.",
|
|
96
|
+
),
|
|
90
97
|
createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
|
|
91
98
|
})
|
|
92
99
|
.describe(
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What a hook is handed beside its event and the D1 binding: the Worker it runs in.
|
|
6
|
+
*
|
|
7
|
+
* `env` is the Worker's environment, typed as the adopter's own through `auth<Env>()` or
|
|
8
|
+
* `organization.withEnv<Env>()(...)`, so a hook can read a secret, start a Workflow or send to a queue. `waitUntil` is the request's
|
|
9
|
+
* `ExecutionContext.waitUntil`, already bound, present when the hook fires inside a request and absent when it fires
|
|
10
|
+
* from a purge Workflow, which has no `ExecutionContext` — a Workflow step already runs to completion.
|
|
11
|
+
*/
|
|
12
|
+
export interface HookRuntime<Env = Record<string, unknown>> {
|
|
13
|
+
/** The Worker's environment: every binding and secret. */
|
|
14
|
+
readonly env: Env;
|
|
15
|
+
/** Keep work running after the response, inside a request. Absent in a Workflow. */
|
|
16
|
+
readonly waitUntil?: (promise: Promise<unknown>) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** What {@link requestRuntime} reads off a Hono context. */
|
|
20
|
+
interface RuntimeSource {
|
|
21
|
+
readonly env: unknown;
|
|
22
|
+
readonly executionCtx?: { waitUntil(promise: Promise<unknown>): void } | undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The runtime for a hook fired inside a request: the request's env, and its `waitUntil` bound to the context.
|
|
27
|
+
*
|
|
28
|
+
* Hono's `executionCtx` getter throws when the request carries none, as under `app.request()` with no context, so
|
|
29
|
+
* that case reads as absent rather than failing the hook's caller.
|
|
30
|
+
*/
|
|
31
|
+
export function requestRuntime<Env = Record<string, unknown>>(c: RuntimeSource): HookRuntime<Env> {
|
|
32
|
+
const env = c.env as Env;
|
|
33
|
+
let ctx: RuntimeSource["executionCtx"];
|
|
34
|
+
try {
|
|
35
|
+
ctx = c.executionCtx;
|
|
36
|
+
} catch {
|
|
37
|
+
ctx = undefined;
|
|
38
|
+
}
|
|
39
|
+
if (!ctx) return { env };
|
|
40
|
+
return { env, waitUntil: ctx.waitUntil.bind(ctx) };
|
|
41
|
+
}
|
package/src/http/adminRoutes.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
|
|
|
9
9
|
import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
|
|
10
10
|
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
|
|
11
11
|
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
12
|
+
import { composedTranslator } from "@pithy-sh/core/src/i18n/composed";
|
|
12
13
|
import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
|
|
13
14
|
import type { Context, Hono } from "hono";
|
|
14
15
|
import type { z } from "zod";
|
|
@@ -859,13 +860,19 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
|
|
|
859
860
|
{ action: AuthAuditActions.adminUserExported, ...call.audit },
|
|
860
861
|
async () => {
|
|
861
862
|
const database = db(c, wiring);
|
|
862
|
-
await requirePresent(database, userId);
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
863
|
+
const { locale } = await requirePresent(database, userId);
|
|
864
|
+
// A retained basis is told to the person, so it is read in their stored locale, never the caller's.
|
|
865
|
+
const t = composedTranslator(wiring.composed ?? [], locale);
|
|
866
|
+
return purgeExports(
|
|
867
|
+
wiring.purgeSteps ?? [],
|
|
868
|
+
{
|
|
869
|
+
subject: { type: "user", id: userId },
|
|
870
|
+
env: c.env as Record<string, unknown>,
|
|
871
|
+
// A capability holding rows by address — a suppression, a tester's membership — reads it here.
|
|
872
|
+
address: () => purgeAddress(database, userId),
|
|
873
|
+
},
|
|
874
|
+
t ? (key) => t.maybe(key) : undefined,
|
|
875
|
+
);
|
|
869
876
|
},
|
|
870
877
|
() => false,
|
|
871
878
|
);
|
package/src/http/resolve.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { Context } from "hono";
|
|
|
12
12
|
import type { AuthWiring } from "../capability";
|
|
13
13
|
import { authDatabase } from "../data/tables";
|
|
14
14
|
import { makeSendAuthEmail, type ResolveRecipientLocale } from "../email/send";
|
|
15
|
+
import { requestRuntime } from "../hooks/runtime";
|
|
15
16
|
import { type AuthInstance, makeAuth } from "../instance/auth";
|
|
16
17
|
import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption";
|
|
17
18
|
import { resolveProvider } from "../instance/providers";
|
|
@@ -133,10 +134,13 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
133
134
|
const baseURL = baseURLResolver(cfg.baseURL)(c.req.raw);
|
|
134
135
|
return makeAuth({
|
|
135
136
|
db: authDatabase(d1),
|
|
136
|
-
// The adopter's listener, bound to *this* request's binding. The instance is built per request, so
|
|
137
|
-
// there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
|
|
138
|
-
|
|
139
|
-
|
|
137
|
+
// The adopter's listener, bound to *this* request's binding and runtime. The instance is built per request, so
|
|
138
|
+
// there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and has none.
|
|
139
|
+
...(listener
|
|
140
|
+
? {
|
|
141
|
+
onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1, requestRuntime(c)),
|
|
142
|
+
}
|
|
143
|
+
: {}),
|
|
140
144
|
secret,
|
|
141
145
|
sessionSecrets,
|
|
142
146
|
// Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
|
package/src/http/responses.ts
CHANGED
|
@@ -475,7 +475,13 @@ const exportEntry = {
|
|
|
475
475
|
.string()
|
|
476
476
|
.optional()
|
|
477
477
|
.describe(
|
|
478
|
-
"For a `retain` entry, why the rows are kept, in one sentence written for the person — `Kept for tax records.` Absent for `erase`.",
|
|
478
|
+
"For a `retain` entry, why the rows are kept, in one sentence written for the person and in their stored locale where a catalog translates it — `Kept for tax records.` Absent for `erase`.",
|
|
479
|
+
),
|
|
480
|
+
basisKey: z
|
|
481
|
+
.string()
|
|
482
|
+
.optional()
|
|
483
|
+
.describe(
|
|
484
|
+
"For a `retain` entry, the catalog key `basis` was translated from, under the capability's own domain — `payments/purge.retained`. Absent when the capability names none, for `erase`, and from a Worker that predates it.",
|
|
479
485
|
),
|
|
480
486
|
};
|
|
481
487
|
|
|
@@ -574,6 +580,28 @@ export const HandoffExchangeResponse = z
|
|
|
574
580
|
.describe("The session a redirect sign-in made, handed to the native app that started it.");
|
|
575
581
|
export type HandoffExchangeResponse = z.output<typeof HandoffExchangeResponse>;
|
|
576
582
|
|
|
583
|
+
/** `POST {base}/attestation/challenge`. */
|
|
584
|
+
export const AttestationChallengeResponse = z
|
|
585
|
+
.object({
|
|
586
|
+
challenge: z
|
|
587
|
+
.string()
|
|
588
|
+
.describe(
|
|
589
|
+
"The challenge: 32 random bytes, unpadded base64url. Good once, on one send route, until `expiresAt`. The platform's assertion is made over SHA-256 of these characters followed by that request's exact body.",
|
|
590
|
+
),
|
|
591
|
+
expiresAt: z.iso.datetime().describe("When the challenge stops being accepted, ISO-8601."),
|
|
592
|
+
})
|
|
593
|
+
.describe("A single-use challenge for a native app attestation.");
|
|
594
|
+
export type AttestationChallengeResponse = z.output<typeof AttestationChallengeResponse>;
|
|
595
|
+
|
|
596
|
+
/** `POST {base}/attestation/ios/keys`. */
|
|
597
|
+
export const AppAttestKeyResponse = z
|
|
598
|
+
.object({
|
|
599
|
+
keyId: z.string().describe("The key identifier, as the request sent it. Assertions name it as `keyId`."),
|
|
600
|
+
registeredAt: z.iso.datetime().describe("When the key was registered, ISO-8601."),
|
|
601
|
+
})
|
|
602
|
+
.describe("An App Attest key this server verified and registered.");
|
|
603
|
+
export type AppAttestKeyResponse = z.output<typeof AppAttestKeyResponse>;
|
|
604
|
+
|
|
577
605
|
/** One of the caller's own registered devices. */
|
|
578
606
|
export const MyDeviceView = z
|
|
579
607
|
.object({
|
package/src/http/routes.ts
CHANGED
|
@@ -8,10 +8,18 @@ import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
|
|
|
8
8
|
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
9
9
|
import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
|
|
10
10
|
import { announceSessionRotated } from "@pithy-sh/core/src/session/rotated";
|
|
11
|
+
import { workerIdentity } from "@pithy-sh/core/src/worker/identity";
|
|
11
12
|
import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
|
|
12
13
|
import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
|
|
13
14
|
import type { Context, Hono } from "hono";
|
|
14
15
|
import { userSessionTokens } from "../admin/users";
|
|
16
|
+
import { APPLE_APP_ATTESTATION_ROOT } from "../attestation/appAttest/root";
|
|
17
|
+
import { registerAppAttestKey } from "../attestation/appAttest/verifier";
|
|
18
|
+
import { issueChallenge } from "../attestation/challenge";
|
|
19
|
+
import { attestationIsConfigured } from "../attestation/config";
|
|
20
|
+
import { AttestationFailedError } from "../attestation/errors";
|
|
21
|
+
import { assertAttestationBlock, sendGate } from "../attestation/gate";
|
|
22
|
+
import { PLATFORM_VERIFIERS } from "../attestation/verifier";
|
|
15
23
|
import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit";
|
|
16
24
|
import type { AuthWiring } from "../capability";
|
|
17
25
|
import { authDatabase } from "../data/tables";
|
|
@@ -39,12 +47,20 @@ import { collapseProviderRefusal } from "./providerRefusal";
|
|
|
39
47
|
import { getAuthInstance, resolveDb } from "./resolve";
|
|
40
48
|
import {
|
|
41
49
|
AccountDeleteResponse,
|
|
50
|
+
AppAttestKeyResponse,
|
|
51
|
+
AttestationChallengeResponse,
|
|
42
52
|
HandoffExchangeResponse,
|
|
43
53
|
MyDeviceRevokeResponse,
|
|
44
54
|
MyDevicesResponse,
|
|
45
55
|
TokenRotateResponse,
|
|
46
56
|
} from "./responses";
|
|
47
|
-
import {
|
|
57
|
+
import {
|
|
58
|
+
AppAttestKeyBody,
|
|
59
|
+
DeleteAccountBody,
|
|
60
|
+
HandoffExchangeBody,
|
|
61
|
+
RevokeDeviceBody,
|
|
62
|
+
SocialSignInStartQuery,
|
|
63
|
+
} from "./schemas";
|
|
48
64
|
import { accountDeletionView } from "./views";
|
|
49
65
|
|
|
50
66
|
type Ctx = Context<PithyHonoEnv>;
|
|
@@ -59,6 +75,9 @@ const BETTER_AUTH_ANSWER: RouteResponse = {
|
|
|
59
75
|
contentType: "application/json",
|
|
60
76
|
};
|
|
61
77
|
|
|
78
|
+
/** The routes that send a sign-in email, under `basePath`: the ones Turnstile and attestation gate. */
|
|
79
|
+
export const SEND_ROUTES = ["/sign-in/magic-link", "/email-otp/send-verification-otp"] as const;
|
|
80
|
+
|
|
62
81
|
function db(c: Ctx, wiring: AuthWiring) {
|
|
63
82
|
return authDatabase(resolveDb(c.env, wiring.config.database));
|
|
64
83
|
}
|
|
@@ -66,7 +85,7 @@ function db(c: Ctx, wiring: AuthWiring) {
|
|
|
66
85
|
/**
|
|
67
86
|
* Register the auth routes onto the backend's Hono app.
|
|
68
87
|
*
|
|
69
|
-
* Order matters:
|
|
88
|
+
* Order matters: Turnstile and attestation gate the send routes ({@link SEND_ROUTES}), Pithy's own
|
|
70
89
|
* routes are registered before the catch-all so they win, and Better Auth owns everything else under
|
|
71
90
|
* `basePath`. A handler that returns a Response ends the chain, so the specific routes never fall
|
|
72
91
|
* through to the catch-all. (The tier-1 edge rate limiter is contributed as capability *middleware*, so
|
|
@@ -77,6 +96,8 @@ function db(c: Ctx, wiring: AuthWiring) {
|
|
|
77
96
|
* | Route | Verification | Input |
|
|
78
97
|
* | -------------------------- | --------------- | --------------------------- |
|
|
79
98
|
* | `POST /token/rotate` | bearer/session | none — the credential only |
|
|
99
|
+
* | `POST /attestation/challenge` | public | none |
|
|
100
|
+
* | `POST /attestation/ios/keys` | public | json `AppAttestKeyBody` |
|
|
80
101
|
* | `GET /sign-in/social/start` | public | query `SocialSignInStartQuery` |
|
|
81
102
|
* | `POST /handoff` | public | json `HandoffExchangeBody` |
|
|
82
103
|
* | `GET /devices` | bearer/session | none |
|
|
@@ -103,15 +124,54 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
|
|
|
103
124
|
// resolved, and reads it back here rather than binding a second copy of the same decision.
|
|
104
125
|
const csrf = requireSameOrigin();
|
|
105
126
|
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
127
|
+
// The magic-link and OTP send routes are gated by Turnstile when it is composed, and by native app
|
|
128
|
+
// attestation once any environment has a block (`../attestation/gate.ts` holds the rule between the two).
|
|
129
|
+
// The Turnstile action is `@pithy-sh/turnstile`'s constant, never a literal: the widget is solved for the
|
|
130
|
+
// same string through the client projection, and two copies disagreeing refuses every sign-in.
|
|
131
|
+
const humanity = wiring.turnstile
|
|
132
|
+
? turnstile({
|
|
133
|
+
mode: wiring.turnstile.mode,
|
|
134
|
+
field: wiring.turnstile.token.field,
|
|
135
|
+
header: wiring.turnstile.token.header,
|
|
136
|
+
action: TURNSTILE_LOGIN_ACTION,
|
|
137
|
+
})
|
|
138
|
+
: undefined;
|
|
139
|
+
const { attestation } = wiring.config;
|
|
140
|
+
const guard = attestationIsConfigured(attestation)
|
|
141
|
+
? sendGate({
|
|
142
|
+
attestation,
|
|
143
|
+
database: wiring.config.database,
|
|
144
|
+
verifiers: wiring.attestationVerifiers ?? PLATFORM_VERIFIERS,
|
|
145
|
+
turnstile: humanity,
|
|
146
|
+
})
|
|
147
|
+
: humanity;
|
|
148
|
+
if (guard) {
|
|
149
|
+
for (const path of SEND_ROUTES) app.use(`${base}${path}`, guard);
|
|
150
|
+
}
|
|
151
|
+
if (attestationIsConfigured(attestation)) {
|
|
152
|
+
app.post(
|
|
153
|
+
`${base}/attestation/challenge`,
|
|
154
|
+
describeRoute({
|
|
155
|
+
summary: "Issue a single-use challenge for a native app attestation.",
|
|
156
|
+
description:
|
|
157
|
+
"A native app asks for one before each send. It attests over SHA-256 of the challenge followed by the send's exact body, and sends the result in the `x-pithy-attestation` header: unpadded base64url over the JSON `{ platform, challenge, assertion, keyId? }`. The challenge is good once, pass or fail, until `expiresAt`. An environment with no attestation block answers `auth/attestation_config`.",
|
|
158
|
+
verification: ["public"],
|
|
159
|
+
responses: { 200: AttestationChallengeResponse },
|
|
160
|
+
}),
|
|
161
|
+
(c) => issueAttestationChallenge(c, wiring),
|
|
162
|
+
);
|
|
163
|
+
app.post(
|
|
164
|
+
`${base}/attestation/ios/keys`,
|
|
165
|
+
describeRoute({
|
|
166
|
+
summary: "Register an iOS app's App Attest key, with Apple's attestation of it.",
|
|
167
|
+
description:
|
|
168
|
+
"Once per key, before its first assertion. The app asks for a challenge, passes SHA-256 of its characters to `attestKey` as the client data hash, and sends the key id and the attestation object here. The certificate chain must lead to Apple App Attestation Root CA, the `rpIdHash` must be an allowed app's, and the key must be from Apple's production environment, or from either in dev, staging and a feature deployment. Then each send carries an assertion by this key in `x-pithy-attestation`. Any check that fails, a key already registered included, answers `auth/attestation_failed`; an environment with no attestation block answers `auth/attestation_config`.",
|
|
169
|
+
verification: ["public"],
|
|
170
|
+
responses: { 200: AppAttestKeyResponse },
|
|
171
|
+
}),
|
|
172
|
+
validate("json", AppAttestKeyBody),
|
|
173
|
+
(c) => registerIosKey(c, wiring, c.req.valid("json")),
|
|
174
|
+
);
|
|
115
175
|
}
|
|
116
176
|
|
|
117
177
|
// Rotate the refresh credential: mint a new session, revoke the presented one, return a fresh JWT.
|
|
@@ -181,7 +241,7 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
|
|
|
181
241
|
(c) => revokeMyDevice(c, wiring, c.req.valid("json")),
|
|
182
242
|
);
|
|
183
243
|
|
|
184
|
-
// The signed-in person deletes their own account
|
|
244
|
+
// The signed-in person deletes their own account — always soft, on the configured window. The one
|
|
185
245
|
// route a suspended account still reaches: the app stores require that somebody can always leave, and a
|
|
186
246
|
// suspension is no reason to keep them. CSRF-guarded as a mutating route; the subject is the session's own,
|
|
187
247
|
// and nothing in the body can name another.
|
|
@@ -300,9 +360,9 @@ function isSignInAttempt(path: string): boolean {
|
|
|
300
360
|
* (`better-call@1.4.0`, `dist/router.mjs:83-89`), which renders an `APIError` as a Response and returns
|
|
301
361
|
* it. The throw is swallowed one frame later by the library that asked for it.
|
|
302
362
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
363
|
+
* A refusal recorded by catching an `APIError` would therefore never be recorded: no failed one-time code,
|
|
364
|
+
* no bad magic link, no refused OAuth callback, which is the largest class of security event this
|
|
365
|
+
* capability has.
|
|
306
366
|
*
|
|
307
367
|
* **The body is cloned, never consumed.** The Response is handed back to the caller untouched: Better
|
|
308
368
|
* Auth's own flat shape is a contract adopters read through `createAuthClient`, and the browser client
|
|
@@ -332,12 +392,11 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
|
|
|
332
392
|
/**
|
|
333
393
|
* Delegate to Better Auth's fetch handler, and record what it refused.
|
|
334
394
|
*
|
|
335
|
-
* **The answer is returned exactly as Better Auth wrote it
|
|
336
|
-
*
|
|
337
|
-
*
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
* contract. `readFailure` in `../client/api` learns to read it instead (#449).
|
|
395
|
+
* **The answer is returned exactly as Better Auth wrote it, never re-homed in the kit envelope.**
|
|
396
|
+
* `packages/auth/README.md` documents `createAuthClient` from `better-auth/client` as a first-class client
|
|
397
|
+
* surface, and `@better-fetch/fetch` builds its error as `{ ...parsedBody, status }`, so rewriting the body
|
|
398
|
+
* would make `error.code` `undefined` for every adopter on the documented path. The wire is Better Auth's
|
|
399
|
+
* contract, and `readFailure` in `../client/api` reads it.
|
|
341
400
|
*
|
|
342
401
|
* The `catch` covers what better-call genuinely hands on: a non-`APIError` throw from an endpoint
|
|
343
402
|
* (`router.mjs:88`), and a throw from a plugin's `onRequest` hook, which runs outside the router's own
|
|
@@ -347,7 +406,7 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
|
|
|
347
406
|
async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
348
407
|
const instance = await getAuthInstance(c, wiring);
|
|
349
408
|
|
|
350
|
-
// **A suspended or deleted account does not reach Better Auth as itself
|
|
409
|
+
// **A suspended or deleted account does not reach Better Auth as itself.** The session middleware
|
|
351
410
|
// has already refused it an `AuthContext`, but Better Auth resolves its own session on these endpoints and
|
|
352
411
|
// would happily mint a `/token` for it. So its verdict is applied here too, on every endpoint that acts as
|
|
353
412
|
// the credential's holder — and not on the ones that end a session or start a new one. `./lifecycleGate`
|
|
@@ -356,7 +415,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
356
415
|
const refusal = noticedRefusal(c);
|
|
357
416
|
if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
|
|
358
417
|
|
|
359
|
-
// **The first of the two guards on the refusal redirect
|
|
418
|
+
// **The first of the two guards on the refusal redirect.** `errorCallbackURL` is the caller's
|
|
360
419
|
// string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
|
|
361
420
|
// whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
|
|
362
421
|
// the kit produced, or refuses it — and carries the argument for why guarding the input is not the same
|
|
@@ -390,7 +449,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
390
449
|
}
|
|
391
450
|
|
|
392
451
|
// **The enumeration oracle on the social callback, closed here because here is the only place both
|
|
393
|
-
// halves are in reach
|
|
452
|
+
// halves are in reach.** A refused social sign-in redirects with a code that says whether an
|
|
394
453
|
// account exists at the address the provider handed over; `./providerRefusal` carries the full
|
|
395
454
|
// argument and the roster. The collapse has to happen where the capability hands the response back,
|
|
396
455
|
// rather than in an adopter's middleware, for a reason this line demonstrates: middleware could
|
|
@@ -408,9 +467,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
408
467
|
// a 302 is also what a *successful* OAuth callback answers with, so `auditRefusal` — which knows
|
|
409
468
|
// only a status and a JSON body — would either read every completed social sign-in as a denial or
|
|
410
469
|
// have to re-derive this decision from the Location header it is not looking at. The refusal is
|
|
411
|
-
// recorded from the one place that has already established it is a refusal and knows which one
|
|
412
|
-
// these refusals reach `pithy_audit_events` for the first time (#449 closed the same gap for the
|
|
413
|
-
// JSON refusals and could not see this one, because it is not a JSON refusal).
|
|
470
|
+
// recorded from the one place that has already established it is a refusal and knows which one.
|
|
414
471
|
await emitDenied(c.var.emit, { ...correlation(c.req.raw.headers), detail: collapsed.reason });
|
|
415
472
|
return collapsed.response;
|
|
416
473
|
}
|
|
@@ -442,7 +499,7 @@ const ROTATION_REUSE_GRACE_MS = 30_000;
|
|
|
442
499
|
* token + refresh token. This is the "refresh credential rotates on use" primitive Better Auth does not
|
|
443
500
|
* provide natively.
|
|
444
501
|
*
|
|
445
|
-
* Two hardenings over a naive rotate
|
|
502
|
+
* Two hardenings over a naive rotate:
|
|
446
503
|
* - **Reuse detection.** A presented token that no longer resolves to a live session but was previously
|
|
447
504
|
* consumed is a replayed refresh token — the compromise signal for rotated refresh tokens
|
|
448
505
|
* (RFC 6819 §5.2.2.3). The whole family is revoked and the attempt denied. (Covers the bearer refresh
|
|
@@ -489,7 +546,7 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
489
546
|
});
|
|
490
547
|
}
|
|
491
548
|
|
|
492
|
-
// An account that may not act gets no successor
|
|
549
|
+
// An account that may not act gets no successor. `session.create.before` would refuse the mint below
|
|
493
550
|
// anyway; refusing here, from the middleware's verdict, is what keeps the presented token unspent and the
|
|
494
551
|
// successor never written, so a reinstated account's device still holds a credential that works.
|
|
495
552
|
const refusal = noticedRefusal(c);
|
|
@@ -509,15 +566,13 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
509
566
|
// **And carry the authentication instant, which is the whole point of the column.** A rotation is the
|
|
510
567
|
// same authentication continuing, not a new one — `createSession` would otherwise stamp `createdAt`
|
|
511
568
|
// afresh and leave the freshness gate measuring nothing, resettable by anyone holding a stolen refresh
|
|
512
|
-
// token
|
|
569
|
+
// token.
|
|
513
570
|
//
|
|
514
|
-
// **A session
|
|
515
|
-
//
|
|
516
|
-
//
|
|
517
|
-
//
|
|
518
|
-
//
|
|
519
|
-
// into one that fails open, on upgrade day, for the whole pre-migration population. `null` travels
|
|
520
|
-
// instead, the gate keeps refusing, and one real sign-in fixes it permanently.
|
|
571
|
+
// **A session with no authentication instant carries `null` forward, never `createdAt`.**
|
|
572
|
+
// `internal-adapter.mjs:275` stamps `createdAt` *after* the caller's override, so a row's `created_at` is
|
|
573
|
+
// the moment of its most recent rotation, and substituting it would hand that session an instant minutes
|
|
574
|
+
// old — freshest for exactly the actor rotating a stolen token. `null` keeps the gate refusing until one
|
|
575
|
+
// real sign-in.
|
|
521
576
|
const authenticatedAt = session.authenticatedAt ?? null;
|
|
522
577
|
|
|
523
578
|
// Mint the successor session and its access token BEFORE consuming the old one, so a transient signing
|
|
@@ -586,7 +641,7 @@ async function listMyDevices(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
586
641
|
}
|
|
587
642
|
|
|
588
643
|
/**
|
|
589
|
-
* Delete the caller's own account
|
|
644
|
+
* Delete the caller's own account: soft, on the configured window, audited as `auth/user_self_deleted`
|
|
590
645
|
* with them as the actor, and every session they hold ended after the columns are written — through Better
|
|
591
646
|
* Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
|
|
592
647
|
*/
|
|
@@ -674,3 +729,38 @@ async function serveMyImage(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
674
729
|
headers: { "content-type": bytes.type, ...STORED_IMAGE_HEADERS },
|
|
675
730
|
});
|
|
676
731
|
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Verify an App Attest attestation against the environment's iOS apps and, when it holds, store the
|
|
735
|
+
* key so its later assertions verify. A failed attestation answers `auth/attestation_failed`.
|
|
736
|
+
*/
|
|
737
|
+
async function registerIosKey(c: Ctx, wiring: AuthWiring, body: AppAttestKeyBody): Promise<Response> {
|
|
738
|
+
const environment = workerIdentity(c.env).environment;
|
|
739
|
+
const settings = assertAttestationBlock(wiring.config.attestation, environment);
|
|
740
|
+
const now = new Date();
|
|
741
|
+
const verdict = await registerAppAttestKey({
|
|
742
|
+
db: db(c, wiring),
|
|
743
|
+
challenge: body.challenge,
|
|
744
|
+
keyId: body.keyId,
|
|
745
|
+
attestation: body.attestation,
|
|
746
|
+
apps: settings.ios,
|
|
747
|
+
environment,
|
|
748
|
+
root: wiring.appAttestRoot ?? APPLE_APP_ATTESTATION_ROOT,
|
|
749
|
+
now,
|
|
750
|
+
});
|
|
751
|
+
if (!verdict.ok) throw new AttestationFailedError({ detail: verdict.reason });
|
|
752
|
+
c.header("cache-control", "no-store");
|
|
753
|
+
return c.json({ keyId: body.keyId, registeredAt: now.toISOString() } satisfies AppAttestKeyResponse);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Issue an attestation challenge, where this environment has a block to judge its use by. */
|
|
757
|
+
async function issueAttestationChallenge(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
758
|
+
const { attestation } = wiring.config;
|
|
759
|
+
assertAttestationBlock(attestation, workerIdentity(c.env).environment);
|
|
760
|
+
const issued = await issueChallenge(db(c, wiring), { now: new Date(), expiresIn: attestation.challengeExpiresIn });
|
|
761
|
+
c.header("cache-control", "no-store");
|
|
762
|
+
return c.json({
|
|
763
|
+
challenge: issued.challenge,
|
|
764
|
+
expiresAt: issued.expiresAt.toISOString(),
|
|
765
|
+
} satisfies AttestationChallengeResponse);
|
|
766
|
+
}
|