ref0-git 0.6.0 → 0.8.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.
Files changed (59) hide show
  1. package/app/apps/github/README.md +3 -7
  2. package/app/apps/github/generated/git-rest.ts +17 -20
  3. package/app/apps/github/src/clients/allowed.ts +7 -9
  4. package/app/apps/github/src/clients/avatars.ts +5 -3
  5. package/app/apps/github/src/clients/graphql.ts +12 -2
  6. package/app/apps/github/src/clients/host-calls.ts +2 -1
  7. package/app/apps/github/src/clients/transfers.ts +56 -19
  8. package/app/apps/github/src/components/signin/device-card.tsx +2 -2
  9. package/app/apps/github/src/context/context.ts +5 -5
  10. package/app/apps/github/src/context/host.ts +115 -0
  11. package/app/apps/github/src/ingress.ts +28 -0
  12. package/app/apps/github/src/policy.ts +113 -78
  13. package/app/apps/github/src/private-repos.ts +7 -7
  14. package/app/apps/github/src/pulls/review.ts +2 -1
  15. package/app/apps/github/src/releases/release-form.tsx +40 -4
  16. package/app/apps/github/src/releases/releases.ts +148 -22
  17. package/app/apps/github/src/routes/uploads/$owner/$repo/$release.tsx +9 -2
  18. package/app/apps/github/src/seed/seed.ts +68 -38
  19. package/app/apps/github/src/server.ts +28 -11
  20. package/app/apps/github/src/signin/approval.ts +20 -15
  21. package/app/apps/github/src/signin/attempts.ts +306 -0
  22. package/app/apps/github/src/signin/auth.ts +9 -0
  23. package/app/apps/github/src/signin/device-code.ts +2 -2
  24. package/app/apps/github/src/signin/device-prompt.ts +6 -6
  25. package/app/apps/github/src/signin/host-session.ts +30 -18
  26. package/app/apps/github/src/signin/limits.ts +35 -0
  27. package/app/pnpm-workspace.yaml +39 -38
  28. package/dist/cli/events.mjs +10 -13
  29. package/dist/cli/failure.mjs +4 -10
  30. package/dist/cli/hosts.mjs +2 -2
  31. package/dist/cli/queue.mjs +14 -23
  32. package/dist/cli/repos.mjs +10 -19
  33. package/dist/cli/resources.mjs +2 -2
  34. package/dist/cli/setup.mjs +33 -40
  35. package/dist/cli/sign-in.mjs +4 -4
  36. package/dist/cli/tokens.mjs +7 -11
  37. package/dist/cli/vendor.mjs +21 -1
  38. package/dist/init/app.mjs +45 -23
  39. package/dist/init/astro.mjs +2 -2
  40. package/dist/init/cloudflare.mjs +100 -51
  41. package/dist/init/create.mjs +1 -1
  42. package/dist/init/detect.mjs +7 -5
  43. package/dist/init/files.mjs +6 -1
  44. package/dist/init/git-module.mjs +89 -32
  45. package/dist/init/metadata.mjs +12 -7
  46. package/dist/init/mounts.mjs +12 -20
  47. package/dist/init/next.mjs +1 -1
  48. package/dist/init/node-app.mjs +5 -2
  49. package/dist/init/node.mjs +24 -35
  50. package/dist/init/nuxt.mjs +6 -7
  51. package/dist/init/react-router.mjs +2 -2
  52. package/dist/init/routes.mjs +13 -22
  53. package/dist/init/stores.mjs +3 -2
  54. package/dist/init/sveltekit.mjs +3 -3
  55. package/dist/init/template.mjs +14 -15
  56. package/dist/init/templates.mjs +76 -81
  57. package/dist/init/vercel.mjs +18 -22
  58. package/dist/init/versions.mjs +32 -4
  59. package/package.json +13 -13
@@ -0,0 +1,306 @@
1
+ import { signInPaths } from '@ref0/git/auth';
2
+ import { Records } from '@ref0/infra';
3
+ import * as Clock from 'effect/Clock';
4
+ import * as Effect from 'effect/Effect';
5
+ import * as Schema from 'effect/Schema';
6
+
7
+ import { deviceAttemptLimits as limits } from './limits.ts';
8
+
9
+ /**
10
+ * The device page's front door (Q635, #1962): every GET and POST to `/login/device` spends an
11
+ * attempt, in the host's records, before Git reads the code it carries. An attempt needs room in
12
+ * three buckets of the window: the host's, the caller's address's and, signed in, its session's.
13
+ * Every ingress of a host shares the one scope, so every isolate and process counts together.
14
+ *
15
+ * The rows, in one collection of one scope, never named from the request:
16
+ * - `host`, `{ window, used }`: the host's attempts in its latest window, which never moves back,
17
+ * so a clock that does reopens no window;
18
+ * - `<window>.<key>`, `{ used }`: an address's or a session's attempts in that window, its key a
19
+ * SHA-256 of what it counts, so no row holds an address or a session.
20
+ *
21
+ * An admitted attempt deletes up to `limits.cleanup` rows of past windows and writes at most two,
22
+ * so the rows never pass the host's 100 attempts' 200, and the host's own row.
23
+ */
24
+
25
+ /** The scope every ingress of a host counts in, whatever host name a request names. */
26
+ const scope = 'host/device-attempts';
27
+
28
+ const collection = 'attempts';
29
+
30
+ const hostId = 'host';
31
+
32
+ /** A window's number as its rows' ids start, so the ids of past windows sort before it. */
33
+ const windowId = (window: number) => String(window).padStart(15, '0');
34
+
35
+ const HostRow = Schema.Struct({ window: Schema.Int, used: Schema.Int });
36
+
37
+ const KeyRow = Schema.Struct({ used: Schema.Int });
38
+
39
+ /** The store failed, a row didn't decode, or racing attempts took every try: answered 503. */
40
+ export class DeviceAttemptsUnavailable extends Schema.TaggedError<DeviceAttemptsUnavailable>()(
41
+ 'DeviceAttemptsUnavailable',
42
+ { reason: Schema.String },
43
+ ) {}
44
+
45
+ /** Whether an attempt may reach Git, or else how many seconds until its window ends. */
46
+ export type Admission =
47
+ | { readonly admitted: true }
48
+ | { readonly admitted: false; readonly retryAfter: number };
49
+
50
+ /** Who an attempt counts against: the platform's address for it, and its checked session's ID. */
51
+ export interface Attempter {
52
+ readonly address: string | undefined;
53
+ readonly session?: string | undefined;
54
+ }
55
+
56
+ /** An IPv4 address's four bytes, in decimal with no leading zero, or `undefined`. */
57
+ const ipv4Bytes = (text: string) => {
58
+ const parts = text.split('.');
59
+ if (parts.length !== 4) return undefined;
60
+
61
+ const bytes = parts.map((part) => (/^(?:0|[1-9]\d{0,2})$/.test(part) ? Number(part) : 256));
62
+
63
+ return bytes.every((byte) => byte <= 255) ? bytes : undefined;
64
+ };
65
+
66
+ /** Groups of an IPv6 address's text, or `undefined` for one that isn't hex of one to four digits. */
67
+ const groupsIn = (text: string) => {
68
+ if (text === '') return [];
69
+
70
+ const groups = text.split(':');
71
+
72
+ return groups.every((group) => /^[0-9a-f]{1,4}$/i.test(group))
73
+ ? groups.map((group) => parseInt(group, 16))
74
+ : undefined;
75
+ };
76
+
77
+ /** An IPv6 address's eight 16-bit groups, an IPv4 tail as its last two, or `undefined`. */
78
+ const ipv6Groups = (text: string) => {
79
+ const tailAt = text.lastIndexOf(':') + 1;
80
+ const dotted = text.includes('.');
81
+ const tail = dotted ? ipv4Bytes(text.slice(tailAt)) : [];
82
+ if (tail === undefined) return undefined;
83
+
84
+ const ending = dotted ? [tail[0]! * 256 + tail[1]!, tail[2]! * 256 + tail[3]!] : [];
85
+ const kept = dotted ? text.slice(0, tailAt) : text;
86
+ // An IPv4 tail follows one colon of its own, or the two that stand for zeros.
87
+ const head = dotted && !kept.endsWith('::') ? kept.slice(0, -1) : kept;
88
+ const halves = head.split('::');
89
+ if (halves.length > 2) return undefined;
90
+
91
+ const left = groupsIn(halves[0] ?? '');
92
+ const right = groupsIn(halves[1] ?? '');
93
+ if (left === undefined || right === undefined) return undefined;
94
+
95
+ const missing = 8 - ending.length - left.length - right.length;
96
+ if (halves.length === 1) return missing === 0 ? [...left, ...ending] : undefined;
97
+
98
+ // `::` stands for one zero group or more, never none.
99
+ return missing < 1
100
+ ? undefined
101
+ : [...left, ...Array<number>(missing).fill(0), ...right, ...ending];
102
+ };
103
+
104
+ /**
105
+ * What an address counts as: an IPv4 address, an IPv4-mapped IPv6 one as its IPv4, or an IPv6
106
+ * address's /64, each one spelling for every way to write it. An address missing, or one that
107
+ * isn't either, counts as one `unknown`, so it shares a bucket rather than escaping one.
108
+ */
109
+ export const addressKey = (address: string | undefined) => {
110
+ const text = (address ?? '').trim();
111
+ const v4 = text.includes(':') ? undefined : ipv4Bytes(text);
112
+ if (v4 !== undefined) return `4:${v4.join('.')}`;
113
+
114
+ // A zone names the host's own interface, never another address: its letters as Node's `isIP` takes.
115
+ const zoneAt = text.indexOf('%');
116
+ const zoned = zoneAt === -1 || /^[0-9a-z.:-]+$/i.test(text.slice(zoneAt + 1));
117
+ const bare = zoneAt === -1 ? text : text.slice(0, zoneAt);
118
+ const groups = text.includes(':') && zoned ? ipv6Groups(bare) : undefined;
119
+ if (groups === undefined) return 'unknown';
120
+
121
+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff;
122
+ if (mapped)
123
+ return `4:${[groups[6]! >> 8, groups[6]! & 255, groups[7]! >> 8, groups[7]! & 255].join('.')}`;
124
+
125
+ return `6:${groups
126
+ .slice(0, 4)
127
+ .map((group) => group.toString(16).padStart(4, '0'))
128
+ .join('')}`;
129
+ };
130
+
131
+ /** `text`'s SHA-256, in hex. */
132
+ const sha256 = (text: string) =>
133
+ Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(
134
+ Effect.map((digest) =>
135
+ Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(''),
136
+ ),
137
+ );
138
+
139
+ /** The buckets past the host's an attempter's attempt needs room in: each key and its cap. */
140
+ const bucketsOf = (who: Attempter) =>
141
+ Effect.all([
142
+ Effect.map(sha256(`address:${addressKey(who.address)}`), (hash) => ({
143
+ key: `a${hash}`,
144
+ cap: limits.address,
145
+ })),
146
+ ...(who.session === undefined
147
+ ? []
148
+ : [
149
+ Effect.map(sha256(`session:${who.session}`), (hash) => ({
150
+ key: `s${hash}`,
151
+ cap: limits.session,
152
+ })),
153
+ ]),
154
+ ]);
155
+
156
+ /** The 503 a failed store call, or a row that doesn't decode, answers, by what failed. */
157
+ const unavailable = (error: { readonly _tag: string }) =>
158
+ new DeviceAttemptsUnavailable({ reason: error._tag });
159
+
160
+ const decodeHost = Schema.decodeUnknownEffect(HostRow);
161
+
162
+ const decodeKey = Schema.decodeUnknownEffect(KeyRow);
163
+
164
+ type Buckets = Effect.Success<ReturnType<typeof bucketsOf>>;
165
+
166
+ /**
167
+ * One try at `now`, in `window` or the later one the host's row holds: admitted, refused, or a
168
+ * later window to try in, after a clock behind the host's or a commit another attempt won.
169
+ */
170
+ const tryAt = (buckets: Buckets, now: number, window: number) =>
171
+ Effect.gen(function* () {
172
+ const ids = buckets.map(({ key }) => `${windowId(window)}.${key}`);
173
+ const snapshot = yield* Effect.mapError(
174
+ Records.read(scope, [
175
+ { collection, id: hostId },
176
+ { collection, to: windowId(window), limit: limits.cleanup },
177
+ ...ids.map((id) => ({ collection, id })),
178
+ ]),
179
+ unavailable,
180
+ );
181
+ const [hostRows = [], past = [], ...keyRows] = snapshot.results;
182
+
183
+ const host =
184
+ hostRows[0] === undefined
185
+ ? undefined
186
+ : yield* Effect.mapError(decodeHost(hostRows[0].value), unavailable);
187
+ if (host !== undefined && host.window > window) return { later: host.window } as const;
188
+
189
+ const hostUsed = host?.window === window ? host.used : 0;
190
+ const used = yield* Effect.forEach(keyRows, (rows) =>
191
+ rows[0] === undefined
192
+ ? Effect.succeed(0)
193
+ : Effect.mapError(decodeKey(rows[0].value), unavailable).pipe(
194
+ Effect.map((row) => row.used),
195
+ ),
196
+ );
197
+ const full = hostUsed >= limits.host || buckets.some(({ cap }, at) => (used[at] ?? 0) >= cap);
198
+
199
+ if (full) {
200
+ const ends = (window + 1) * limits.window;
201
+
202
+ return {
203
+ admission: { admitted: false, retryAfter: Math.max(1, Math.ceil((ends - now) / 1000)) },
204
+ } as const;
205
+ }
206
+
207
+ const committed = yield* Effect.mapError(
208
+ Records.commit(scope, {
209
+ id: crypto.randomUUID(),
210
+ expect: snapshot.version,
211
+ put: [
212
+ { collection, id: hostId, value: { window, used: hostUsed + 1 } },
213
+ ...ids.map((id, at) => ({ collection, id, value: { used: (used[at] ?? 0) + 1 } })),
214
+ ],
215
+ delete: past.map((row) => ({ collection, id: row.id })),
216
+ }),
217
+ unavailable,
218
+ );
219
+
220
+ return committed.ok
221
+ ? ({ admission: { admitted: true } } as const)
222
+ : ({ later: window } as const);
223
+ });
224
+
225
+ /**
226
+ * Spends one attempt for `who`, or refuses it, before any code is read. Each try reads the rows
227
+ * again and commits only at the version it read, so racing attempts never admit past a cap; up to
228
+ * `limits.tries` tries, keeping only the latest window a try saw, then `DeviceAttemptsUnavailable`.
229
+ * A committed attempt stays spent, whatever becomes of its request.
230
+ */
231
+ export const admitDeviceAttempt = (who: Attempter) =>
232
+ Effect.gen(function* () {
233
+ const buckets = yield* bucketsOf(who);
234
+ let seen = 0;
235
+
236
+ for (let tries = 0; tries < limits.tries; tries++) {
237
+ const now = yield* Clock.currentTimeMillis;
238
+ const tried = yield* tryAt(buckets, now, Math.max(Math.floor(now / limits.window), seen));
239
+ if ('admission' in tried) return tried.admission;
240
+
241
+ seen = tried.later;
242
+ }
243
+
244
+ return yield* new DeviceAttemptsUnavailable({ reason: 'Racing attempts took every try' });
245
+ });
246
+
247
+ /** A refused attempt's answer: the same whether or not the code exists, and never cached. */
248
+ const refusedPage = (retryAfter: number) =>
249
+ new Response('Too many sign-in attempts: try again later', {
250
+ status: 429,
251
+ headers: {
252
+ 'retry-after': String(retryAfter),
253
+ 'cache-control': 'no-store',
254
+ 'content-type': 'text/plain; charset=utf-8',
255
+ },
256
+ });
257
+
258
+ /** Git's own answer when sign-in's store fails, which a failed front door answers too. */
259
+ const unavailablePage = () =>
260
+ new Response('Sign-in is unavailable: try again', {
261
+ status: 503,
262
+ headers: { 'cache-control': 'no-store', 'content-type': 'text/plain; charset=utf-8' },
263
+ });
264
+
265
+ /** Whether the front door counts a request: a GET or a POST to the device page, Git's 405 else. */
266
+ export const isDeviceAttempt = (pathname: string, method: string) =>
267
+ pathname === signInPaths.device && (method === 'GET' || method === 'POST');
268
+
269
+ /**
270
+ * The front door's answer for an attempt of `who`'s: `undefined` once it's spent, a 429 refused, or
271
+ * Git's 503 when the store fails, a row doesn't decode or racing attempts take every try.
272
+ */
273
+ export const deviceAttemptAnswer = (who: Attempter) =>
274
+ admitDeviceAttempt(who).pipe(
275
+ Effect.map((admission) => (admission.admitted ? undefined : refusedPage(admission.retryAfter))),
276
+ Effect.catchCause(() => Effect.succeed(unavailablePage())),
277
+ );
278
+
279
+ export interface DeviceAttemptGateOptions {
280
+ /** `deviceAttemptAnswer` for `who`, run on the host's runtime, with its records. */
281
+ readonly answer: (who: Attempter) => Promise<Response | undefined>;
282
+ /** The header the platform sets with the caller's address, in place of any the caller sent. */
283
+ readonly addressHeader: string;
284
+ /** The ID of the session Better Auth checked, or `undefined` signed out; a throw answers 503. */
285
+ readonly session?: (request: Request) => Promise<string | undefined>;
286
+ }
287
+
288
+ /**
289
+ * The front door to put before a host's routes: a 429 or a 503 for a device-page request it
290
+ * refuses, or `undefined` for one it admits and for any other request. It reads no body, and runs
291
+ * an attempt without the request's signal, so a caller who hangs up keeps it spent.
292
+ */
293
+ export const deviceAttemptGate =
294
+ (options: DeviceAttemptGateOptions) =>
295
+ async (request: Request): Promise<Response | undefined> => {
296
+ if (!isDeviceAttempt(new URL(request.url).pathname, request.method)) return undefined;
297
+
298
+ try {
299
+ const session = await options.session?.(request);
300
+ const address = request.headers.get(options.addressHeader) ?? undefined;
301
+
302
+ return await options.answer({ address, session });
303
+ } catch {
304
+ return unavailablePage();
305
+ }
306
+ };
@@ -738,6 +738,15 @@ export const sessionFrom =
738
738
  return { login, token, tokenId: held.gitTokenId, expiresAt: found.session.expiresAt.getTime() };
739
739
  };
740
740
 
741
+ /**
742
+ * The ID of the session Better Auth checked for `request`, or `undefined` signed out: what the
743
+ * device page's attempts count a session by, never its cookie, which a caller can change.
744
+ */
745
+ export const sessionIdFrom =
746
+ (auth: StarterAuth) =>
747
+ async (request: Request): Promise<string | undefined> =>
748
+ (await auth.api.getSession({ headers: request.headers }))?.session.id;
749
+
741
750
  /**
742
751
  * Ends the browser's session, once Git refuses its token: Better Auth deletes its row, and the
743
752
  * delete hook revokes the token, so a revoke Git already made only logs its id.
@@ -4,7 +4,7 @@ import { flow } from 'effect/Function';
4
4
  import * as Option from 'effect/Option';
5
5
  import * as Schema from 'effect/Schema';
6
6
 
7
- import type { TokenScope } from '@ref0/git';
7
+ import type { GrantScope } from '@ref0/git';
8
8
 
9
9
  import { clientLabel, openPrompt, openRetry, tokenScopeOf } from './device-prompt.ts';
10
10
 
@@ -27,7 +27,7 @@ export type DeviceCardState =
27
27
  readonly login: string;
28
28
  readonly userCode: string;
29
29
  /** What Approve grants over every repo `login` may reach: `tokenScopeOf` the device's scopes. */
30
- readonly tokenScope: TokenScope;
30
+ readonly tokenScope: GrantScope;
31
31
  /** How many days the token Approve mints lasts. */
32
32
  readonly days: number;
33
33
  /** The scopes the device asked for, which `tokenScope` reaches past `read` only if one names it. */
@@ -1,6 +1,6 @@
1
- import type { DeviceApproval, TokenScope } from '@ref0/git';
1
+ import type { DeviceApproval, GrantScope } from '@ref0/git';
2
2
  import { ghClientId, ghWriteScope } from '@ref0/git/auth';
3
- import { tokenScopes } from '@ref0/git/rest';
3
+ import { grantScopes } from '@ref0/git';
4
4
  import * as Option from 'effect/Option';
5
5
  import * as Schema from 'effect/Schema';
6
6
 
@@ -42,17 +42,17 @@ const promptLife = 10 * 60 * 1000;
42
42
  * unless it names one of these. `public_repo` reads, where GitHub would let it write public repos:
43
43
  * a deliberate narrowing, since a Git token has no write over public repos alone.
44
44
  */
45
- const pastRead: ReadonlyMap<string, TokenScope> = new Map([
45
+ const pastRead: ReadonlyMap<string, GrantScope> = new Map([
46
46
  [ghWriteScope, 'write'],
47
47
  ['repo:status', 'report'],
48
48
  ['repo_deployment', 'report'],
49
49
  ]);
50
50
 
51
51
  /** Approve's token scope: each scope a device asks for maps as GitHub reads it; the widest wins. */
52
- export const tokenScopeOf = (scopes: readonly string[]): TokenScope => {
53
- const reached = scopes.map((scope) => tokenScopes.indexOf(pastRead.get(scope) ?? 'read'));
52
+ export const tokenScopeOf = (scopes: readonly string[]): GrantScope => {
53
+ const reached = scopes.map((scope) => grantScopes.indexOf(pastRead.get(scope) ?? 'read'));
54
54
 
55
- return tokenScopes[Math.max(0, ...reached)] ?? 'read';
55
+ return grantScopes[Math.max(0, ...reached)] ?? 'read';
56
56
  };
57
57
 
58
58
  /**
@@ -1,6 +1,9 @@
1
- import type { GitAuth, NamedActor } from '@ref0/git';
2
- import { bearer } from '@ref0/git/auth';
1
+ import { Auth } from '@ref0/git';
2
+ import type { NamedActor } from '@ref0/git';
3
+ import * as Clock from 'effect/Clock';
4
+ import * as Effect from 'effect/Effect';
3
5
  import * as Option from 'effect/Option';
6
+ import * as Redacted from 'effect/Redacted';
4
7
  import * as Schema from 'effect/Schema';
5
8
 
6
9
  import { loginProblem } from '../names/owners.ts';
@@ -23,6 +26,8 @@ const HostSession = Schema.Struct({ login: Schema.String, expiresAt: Schema.Numb
23
26
 
24
27
  const hostSessionOf = Schema.decodeUnknownOption(Schema.fromJsonString(HostSession));
25
28
 
29
+ const encodeHostSession = Schema.encodeSync(Schema.fromJsonString(HostSession));
30
+
26
31
  /** `request` with no host session on it: what the Worker serves, whoever sent it. */
27
32
  export const withoutHostSession = (request: Request): Request => {
28
33
  if (!request.headers.has(hostSessionHeader)) return request;
@@ -34,11 +39,15 @@ export const withoutHostSession = (request: Request): Request => {
34
39
  };
35
40
 
36
41
  /** The header's value for `login`, sealed under the session key, which opens for a minute. */
37
- export const hostSessionFor = (key: CryptoKey, login: string): Promise<string> =>
38
- seal(key, purpose, JSON.stringify({ login, expiresAt: Date.now() + lifetime }));
42
+ export const hostSessionFor = (key: CryptoKey, login: string): Effect.Effect<string> =>
43
+ Effect.flatMap(Clock.currentTimeMillis, (now) =>
44
+ Effect.promise(() =>
45
+ seal(key, purpose, encodeHostSession({ login, expiresAt: now + lifetime })),
46
+ ),
47
+ );
39
48
 
40
49
  /**
41
- * Git's `auth` for the app: the admin's bearer secret, or, on a request with no credential, a
50
+ * Git's `Auth` for the app: the admin's bearer secret, or, on a request with no credential, a
42
51
  * host session the app's server sealed, as its person, when its login is one. It never reads
43
52
  * Better Auth's cookie, so a browser's session acts only through its capped Git token (Q520). Git's own tokens never reach it: Git reads
44
53
  * them first, and a token's holder stays capped by its scope.
@@ -47,22 +56,25 @@ export const appAuth = (options: {
47
56
  readonly adminToken: string;
48
57
  readonly admin: NamedActor;
49
58
  readonly key: Promise<CryptoKey>;
50
- }): GitAuth => {
51
- const asAdmin = bearer({ token: options.adminToken, actor: options.admin });
59
+ }): Auth.AuthService => {
60
+ const asAdmin = Auth.bearer({ token: Redacted.make(options.adminToken), actor: options.admin });
52
61
 
53
- return async (input) => {
54
- if (input.credentials !== undefined) return asAdmin(input);
62
+ return Auth.make(
63
+ Effect.fnUntraced(function* (input) {
64
+ if (input.credentials !== undefined) return yield* asAdmin.identify(input);
55
65
 
56
- const text = input.request.headers.get(hostSessionHeader);
57
- if (text === null) return undefined;
66
+ const text = input.request.headers.get(hostSessionHeader);
67
+ if (text === null) return Option.none();
58
68
 
59
- const opened = await open(await options.key, purpose, text);
60
- const session = opened === undefined ? Option.none() : hostSessionOf(opened);
61
- if (Option.isNone(session) || session.value.expiresAt <= Date.now()) return undefined;
69
+ const opened = yield* Effect.promise(async () => open(await options.key, purpose, text));
70
+ const session = opened === undefined ? Option.none() : hostSessionOf(opened);
71
+ const now = yield* Clock.currentTimeMillis;
72
+ if (Option.isNone(session) || session.value.expiresAt <= now) return Option.none();
62
73
 
63
- // A person's ID is their login, never the admin's `_admin`, however the session was made.
64
- const login = session.value.login;
74
+ // A person's ID is their login, never the admin's `_admin`, however the session was made.
75
+ const login = session.value.login;
65
76
 
66
- return loginProblem(login) === undefined ? { id: login } : undefined;
67
- };
77
+ return loginProblem(login) === undefined ? Option.some({ id: login }) : Option.none();
78
+ }),
79
+ );
68
80
  };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The device flow's attempt limits (Q635, #1962): how many requests to `/login/device`, the page a
3
+ * person types a code into, a host takes before Git reads any code. Every shipped host reads these
4
+ * numbers from here, the examples through copies `scripts/host-copies.ts` writes.
5
+ *
6
+ * A code lives 900 seconds, so it overlaps at most 16 windows, and the host takes at most
7
+ * 16 × 100 = 1,600 tries at it: one live code of the 32^8 = 2^40 is found with a chance under
8
+ * 1.5 × 10^-9, and N live codes under N times that, however many addresses send them.
9
+ */
10
+ const host = 100;
11
+
12
+ export const deviceAttemptLimits = {
13
+ /** One window's length, in milliseconds, on the host's clock. */
14
+ window: 60_000,
15
+ /** Attempts the whole host takes in a window, from every address and session. */
16
+ host,
17
+ /** Attempts one address takes in a window: an IPv4 address, or an IPv6 address's /64. */
18
+ address: 10,
19
+ /** Attempts one signed-in session takes in a window, whatever address it comes from. */
20
+ session: 5,
21
+ /** Rows of past windows an admitted attempt deletes, at most. */
22
+ cleanup: 4,
23
+ /**
24
+ * Reads and commits one attempt makes before it answers 503, as racing attempts take turns.
25
+ * Only an admitted attempt writes the scope, so a try loses only to another admission, and a
26
+ * full window refuses on its read, writing nothing: an attempt loses at most `host` tries a
27
+ * window. While an attempt stays within two windows it ends in an admit or a 429. Spending
28
+ * every try needs `tries` admissions by others during that one attempt, so only a host
29
+ * saturated across three or more windows answers 503. Each try is a read and a commit: 203
30
+ * tries, 406 store calls, within a Worker's 8,000 subrequests. A window's worst burst, every
31
+ * attempt reading before any commits, costs about 100 × 101 / 2 = 5,050 reads and as many
32
+ * commits.
33
+ */
34
+ tries: 2 * host + 3,
35
+ } as const;