@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 368 lines 11 KB
Raw
1 ---
2 title: "Part 4: Give users their own credentials"
3 description: Replace the shared credential with Better Auth accounts and individual Git API keys.
4 ---
5
6 import PackageManagers from "../../../../components/PackageManagers.astro";
7
8 One shared credential cannot distinguish one caller from another. Replace it
9 with Better Auth accounts and API keys, then use the authenticated user's ID
10 when checking access to a named repository.
11
12 Keep the host and storage from [Part 3](/git/tutorial/part-3). Existing repositories
13 remain in place. This part creates new repositories under user IDs; it does not
14 transfer the existing `acme/web` repository to a user.
15
16 ## Install Better Auth
17
18 <PackageManagers add="@alchemy.run/better-auth better-auth @better-auth/api-key" />
19
20 Better Auth will manage accounts and credentials. Git will continue to store
21 repositories.
22
23 ## Store accounts in D1
24
25 Create `src/auth.ts`:
26
27 ```typescript
28 // src/auth.ts
29 import { BetterAuth } from "@alchemy.run/better-auth";
30 import * as Cloudflare from "@alchemy.run/cloudflare";
31
32 export const AuthDb = Cloudflare.D1.Database("AuthDb");
33
34 export const Auth = BetterAuth({
35 basePath: "/api/auth",
36 emailAndPassword: { enabled: true },
37 });
38 ```
39
40 This enables email/password accounts under `/api/auth`. The host will supply
41 D1 as the database implementation later in this part.
42
43 ## Enable individual API keys
44
45 ```diff lang="typescript"
46 // src/auth.ts
47 import { BetterAuth } from "@alchemy.run/better-auth";
48 +import { apiKey } from "@better-auth/api-key";
49 ```
50
51 Register the plugin:
52
53 ```diff lang="typescript"
54 // src/auth.ts
55 emailAndPassword: { enabled: true },
56 + plugins: [apiKey()],
57 });
58 ```
59
60 A signed-in user can now mint an API key for a Git client. That key replaces the
61 shared credential in the HTTP Basic password field.
62
63 ## Set a request allowance for Git
64
65 ```diff lang="typescript"
66 // src/auth.ts
67 - plugins: [apiKey()],
68 + plugins: [apiKey({
69 + rateLimit: { timeWindow: 60_000, maxRequests: 1_000 },
70 + })],
71 ```
72
73 A push or clone makes multiple authenticated HTTP requests. Set an explicit
74 allowance of 1,000 requests per minute for the keys created in this tutorial;
75 the plugin's default of ten requests per day is too small for these steps.
76
77 ## Represent the caller
78
79 Create `src/session.ts`:
80
81 ```typescript
82 // src/session.ts
83 import * as Context from "effect/Context";
84
85 export class Session extends Context.Service<
86 Session,
87 { readonly user: { readonly id: string } | null }
88 >()("app/Session") {}
89 ```
90
91 This service carries the caller through one request. A user has an ID;
92 `null` represents an anonymous caller reading a public repository.
93
94 ## Resolve a session cookie
95
96 Create `src/credentials.ts`:
97
98 ```typescript
99 // src/credentials.ts
100 import * as Effect from "effect/Effect";
101 import { Auth } from "./auth.ts";
102
103 export const ResolveUser = Effect.gen(function* () {
104 const auth = yield* Auth;
105 return Effect.gen(function* () {
106 const session = yield* auth.getSession().pipe(
107 Effect.catchTag("BetterAuthApiError", () => Effect.succeed(null)),
108 );
109 return session ? { id: session.user.id.toLowerCase() } : null;
110 });
111 });
112 ```
113
114 As with `PublicRead`, the outer effect acquires a dependency and returns a check
115 that runs per request. Better Auth reads the request's session cookie. Lowercase
116 the ID because Git repository owners are normalized to lowercase.
117
118 ## Accept an API key from Git
119
120 Add the HTTP Basic decoder imports:
121
122 ```diff lang="typescript"
123 // src/credentials.ts
124 import * as Effect from "effect/Effect";
125 +import * as Redacted from "effect/Redacted";
126 +import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
127 +import * as HttpApiSecurity from "effect/http-api/HttpApiSecurity";
128 ```
129
130 Check for an API key before looking for a session cookie:
131
132 ```diff lang="typescript"
133 // src/credentials.ts
134 const auth = yield* Auth;
135 return Effect.gen(function* () {
136 + const { password } = yield* HttpApiBuilder.securityDecode(HttpApiSecurity.basic);
137 + const key = Redacted.value(password);
138 + if (key !== "") {
139 + const verified = yield* auth.api.verifyApiKey({ body: { key } }).pipe(
140 + Effect.catchTag("BetterAuthApiError", () =>
141 + Effect.succeed({ valid: false as const, key: null }),
142 + ),
143 + );
144 + return verified.valid && verified.key
145 + ? { id: verified.key.referenceId.toLowerCase() }
146 + : null;
147 + }
148 const session = yield* auth.getSession().pipe(
149 ```
150
151 The key identifies its owner. An invalid key produces an anonymous caller, so
152 it cannot grant access to a private repository or a write operation.
153
154 ## Authorize the identified user
155
156 Replace `src/middleware.ts` with:
157
158 ```typescript
159 // src/middleware.ts
160 import { RuntimeContext } from "alchemy";
161 import * as Effect from "effect/Effect";
162 import * as HttpRouter from "effect/http/HttpRouter";
163 import * as HttpServerResponse from "effect/http/HttpServerResponse";
164 import { ResolveUser } from "./credentials.ts";
165 import { PublicRead } from "./public-read.ts";
166 import { Session } from "./session.ts";
167
168 export const Authentication = HttpRouter.middleware<{ provides: Session }>()(
169 Effect.gen(function* () {
170 const resolveUser = yield* ResolveUser;
171 const publicRead = yield* PublicRead;
172 return (httpEffect) =>
173 Effect.gen(function* () {
174 const user = yield* resolveUser;
175 const { owner } = yield* HttpRouter.params;
176 const own = owner === undefined || owner.toLowerCase() === user?.id;
177 if ((user !== null && own) || (yield* publicRead)) {
178 return yield* Effect.provideService(httpEffect, Session, { user });
179 }
180 return HttpServerResponse.jsonUnsafe(
181 { _tag: "Unauthorized" },
182 { status: 401, headers: { "www-authenticate": 'Basic realm="git"' } },
183 );
184 }).pipe(Effect.provide(RuntimeContext.phantom));
185 }),
186 );
187 ```
188
189 For routes naming an owner, the user's ID must match that owner unless the
190 request is a public read. The middleware also provides `Session` for application
191 handlers to use in Part 5. Routes without an owner parameter require a signed-in
192 user; they do not acquire automatic tenant filtering. This tutorial creates
193 repositories under the caller's ID explicitly.
194
195 ## Serve Better Auth's routes
196
197 Add the auth imports to `src/host.ts`:
198
199 ```diff lang="typescript"
200 // src/host.ts
201 import * as HttpRouter from "effect/http/HttpRouter";
202 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
203 +import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1";
204 +import { Auth, AuthDb } from "./auth.ts";
205 ```
206
207 Initialize Better Auth beside the Git router:
208
209 ```diff lang="typescript"
210 // src/host.ts
211 Effect.gen(function* () {
212 + const auth = yield* Auth;
213 const fetch = yield* HttpRouter.toHttpEffect(
214 ```
215
216 Send `/api/auth` requests to Better Auth. They must be reachable before a user
217 has signed in:
218
219 ```diff lang="typescript"
220 // src/host.ts
221 - return { fetch };
222 + return {
223 + fetch: Effect.gen(function* () {
224 + const request = yield* HttpServerRequest;
225 + const path = request.url.split("?")[0];
226 + if (path === "/api/auth" || path?.startsWith("/api/auth/")) {
227 + return yield* auth.fetch;
228 + }
229 + return yield* fetch;
230 + }),
231 + };
232 ```
233
234 Supply the D1 database on the Worker's initialization effect:
235
236 ```diff lang="typescript"
237 // src/host.ts
238 - }),
239 + }).pipe(Effect.provide(CloudflareD1(AuthDb))),
240 ) {}
241 ```
242
243 The adapter binds D1 to the Worker and runs Better Auth's schema migrations at
244 deploy time. Git's bucket and Durable Objects are unchanged.
245
246 ## Remove the shared credential
247
248 Remove its imports from `alchemy.run.ts`:
249
250 ```diff lang="typescript"
251 // alchemy.run.ts
252 -import * as Output from "alchemy/Output";
253 -import * as Redacted from "effect/Redacted";
254 -import { GitSecret } from "./src/secret.ts";
255 ```
256
257 Return only the URL again:
258
259 ```diff lang="typescript"
260 // alchemy.run.ts
261 const host = yield* GitHost;
262 - const secret = yield* GitSecret;
263 - return {
264 - url: host.url.as<string>(),
265 - secret: Output.map(secret.text, Redacted.value),
266 - };
267 + return { url: host.url.as<string>() };
268 ```
269
270 `src/secret.ts` is now unused and can be deleted. The old credential will no
271 longer authorize requests after the next deploy.
272
273 ## Deploy accounts and credentials
274
275 <PackageManagers run="alchemy deploy" />
276
277 Install `jq` for the following shell checks if you do not already have it.
278 Continue using the same `$HOST`.
279
280 ## Sign up
281
282 ```sh
283 curl --fail-with-body -c dana.cookies \
284 -X POST "$HOST/api/auth/sign-up/email" \
285 -H "Origin: $HOST" -H "Content-Type: application/json" \
286 -d '{"name":"Dana","email":"dana@example.com","password":"tutorial-password-dana"}' \
287 > dana.json
288 export OWNER=$(jq -r '.user.id | ascii_downcase' dana.json)
289 ```
290
291 The response gives you Dana's ID and sets a session cookie. `curl -c` saves that
292 cookie; `curl -b` will send it on later requests. `Origin` is included for Better
293 Auth's checks on requests using cookies.
294
295 If you repeat these steps after creating the account, use `/api/auth/sign-in/email`
296 with the same email and password to obtain a new cookie.
297
298 ## Create a private repository for Dana
299
300 ```sh
301 curl --fail-with-body -b dana.cookies -X POST "$HOST/api/v1/repos" \
302 -H "Origin: $HOST" -H "Content-Type: application/json" \
303 -d "{\"owner\":\"$OWNER\",\"name\":\"web\",\"public\":false}"
304 ```
305
306 This is a new repository named `$OWNER/web`. The earlier `acme/web` remains
307 public and readable, but neither Dana nor another new account owns its namespace.
308
309 ## Mint a Git credential
310
311 ```sh
312 export KEY=$(curl --fail-with-body -b dana.cookies \
313 -X POST "$HOST/api/auth/api-key/create" \
314 -H "Origin: $HOST" -H "Content-Type: application/json" \
315 -d '{"name":"laptop"}' | jq -r .key)
316 ```
317
318 The returned key is the Git password for Dana's account. Save it; Better Auth
319 shows the complete key when it is created.
320
321 ## Push as Dana
322
323 ```sh
324 git -C work remote set-url origin "$HOST/$OWNER/web.git"
325 git -c credential.helper= -C work push -u origin main
326 ```
327
328 Enter `x` as the username and `$KEY` as the password. Clone the private repository
329 with the same key:
330
331 ```sh
332 git -c credential.helper= clone "$HOST/$OWNER/web.git" dana-copy
333 git -C dana-copy fsck --strict
334 ```
335
336 ## Check isolation between users
337
338 Create a second account:
339
340 ```sh
341 curl --fail-with-body -c alex.cookies \
342 -X POST "$HOST/api/auth/sign-up/email" \
343 -H "Origin: $HOST" -H "Content-Type: application/json" \
344 -d '{"name":"Alex","email":"alex@example.com","password":"tutorial-password-alex"}' \
345 > alex.json
346 export ALEX=$(jq -r '.user.id | ascii_downcase' alex.json)
347 ```
348
349 Alex can create a separate private repository:
350
351 ```sh
352 curl --fail-with-body -b alex.cookies -X POST "$HOST/api/v1/repos" \
353 -H "Origin: $HOST" -H "Content-Type: application/json" \
354 -d "{\"owner\":\"$ALEX\",\"name\":\"web\",\"public\":false}"
355 curl -i -b alex.cookies "$HOST/api/v1/repos/$ALEX/web"
356 ```
357
358 Expect `200` for Alex's own repository. Reading Dana's private repository with
359 Alex's cookie must fail:
360
361 ```sh
362 curl -i -b alex.cookies "$HOST/api/v1/repos/$OWNER/web"
363 ```
364
365 Expect `401`. With `dana.cookies` the same request returns `200`.
366
367 [Part 5: Add your application's API](/git/tutorial/part-5) uses `Session` in a
368 route you implement yourself.