ref0-git 0.25.0 → 0.26.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/app/apps/github/README.md +13 -5
- package/app/apps/github/migrations/sql/0001_auth.sql +2 -2
- package/app/apps/github/migrations/sql/0002_passkeys.sql +1 -1
- package/app/apps/github/migrations/sql/0003_orgs.sql +0 -1
- package/app/apps/github/migrations/sql/0004_avatars.sql +0 -1
- package/app/apps/github/migrations/sql/0005_repo_grants.sql +1 -1
- package/app/apps/github/package.json +2 -0
- package/app/apps/github/scripts/serve.ts +219 -0
- package/app/apps/github/src/server.ts +4 -2
- package/app/apps/github/src/signin/auth.ts +37 -12
- package/app/apps/github/src/signin/client-ip.ts +22 -7
- package/app/apps/github/src/signin/migrate.ts +251 -0
- package/app/pnpm-workspace.yaml +10 -0
- package/dist/cli/setup.mjs +1 -1
- package/dist/init/app.mjs +3 -2
- package/dist/init/metadata.mjs +1 -1
- package/dist/init/node-app.mjs +6 -2
- package/dist/init/templates.mjs +4 -3
- package/dist/init/versions.mjs +1 -1
- package/package.json +5 -5
|
@@ -2,20 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
Git, a GitHub-compatible API and a web app over them, in one Cloudflare Worker. Set it up, run it, and change it: its pages and its policy are yours, and the logic is in `@ref0/git` and `@ref0/github`.
|
|
4
4
|
|
|
5
|
-
`ref0-git init` writes it as a project of your own: see [the walk](../../docs/start.md). The commands below are that project's. In this repo, `pnpm install` at the root, `cp .dev.vars.example .dev.vars`, then `pnpm
|
|
5
|
+
`ref0-git init` writes it as a project of your own: see [the walk](../../docs/start.md). The commands below are that project's. In this repo, `pnpm install` at the root, `cp .dev.vars.example .dev.vars`, then `pnpm run dev` here runs it as it is.
|
|
6
6
|
|
|
7
7
|
## Run it locally
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
npx wrangler d1 migrations apply AUTH_DB --local # the people's tables
|
|
11
10
|
npm run dev
|
|
12
11
|
```
|
|
13
12
|
|
|
14
13
|
`init` installed it, and wrote its three secrets, for local use only, in `.dev.vars`.
|
|
15
14
|
|
|
16
|
-
Open http://localhost:5173. The first request seeds a demo: Pip and Mo, who sign in with `.dev.vars`' `DEMO_PASSWORD`, the org `acme`, which Pip owns and Mo belongs to, and its repos `acme/web` in TypeScript, `acme/handbook` in Markdown and `acme/cli` in Go, each with a description and a license, and with history, pull requests, reviews and issues. It runs in workerd, with its objects, its bucket and its D1 on disk in `.wrangler/state`, and needs no Cloudflare account. Delete `.wrangler/state` to start again from an empty host
|
|
15
|
+
Open http://localhost:5173. The first request seeds a demo: Pip and Mo, who sign in with `.dev.vars`' `DEMO_PASSWORD`, the org `acme`, which Pip owns and Mo belongs to, and its repos `acme/web` in TypeScript, `acme/handbook` in Markdown and `acme/cli` in Go, each with a description and a license, and with history, pull requests, reviews and issues. It runs in workerd, with its objects, its bucket and its D1 on disk in `.wrangler/state`, and needs no Cloudflare account. Delete `.wrangler/state` to start again from an empty host.
|
|
17
16
|
|
|
18
|
-
To sign in, sign in at `/login` as `pip` or `mo` with `DEMO_PASSWORD`, or sign up at `/signup` with a login of your own and a password of at least 15 characters. People, orgs, their passwords and their sessions are Better Auth's, in D1: `src/signin/auth.ts` sets it up, and `migrations/sql/` holds its tables, beside Postgres's in `migrations/postgres/`.
|
|
17
|
+
To sign in, sign in at `/login` as `pip` or `mo` with `DEMO_PASSWORD`, or sign up at `/signup` with a login of your own and a password of at least 15 characters. People, orgs, their passwords and their sessions are Better Auth's, in D1: `src/signin/auth.ts` sets it up, and `migrations/sql/` holds its tables, beside Postgres's in `migrations/postgres/`. The app applies them to D1 itself, before its first sign-in, and records each in wrangler's `d1_migrations` table, as `wrangler d1 migrations apply` would.
|
|
19
18
|
|
|
20
19
|
## Deploy it to Cloudflare
|
|
21
20
|
|
|
@@ -23,7 +22,6 @@ It needs Workers Paid: a clone takes more CPU than the free plan gives. Set `APP
|
|
|
23
22
|
|
|
24
23
|
```sh
|
|
25
24
|
npx wrangler d1 create <name>-auth --binding AUTH_DB --update-config
|
|
26
|
-
npx wrangler d1 migrations apply AUTH_DB --remote
|
|
27
25
|
npm run deploy # builds, then runs wrangler deploy
|
|
28
26
|
ADMIN=$(openssl rand -hex 32)
|
|
29
27
|
printf %s "$ADMIN" | npx wrangler secret put ADMIN_TOKEN
|
|
@@ -34,6 +32,16 @@ openssl rand -hex 32 | npx wrangler secret put SESSION_SECRET
|
|
|
34
32
|
|
|
35
33
|
A build for deploying holds none of the demo, so it starts with no repos and no people. Anyone may sign up until `SIGN_UP` is `closed` in `wrangler.jsonc`'s `vars`.
|
|
36
34
|
|
|
35
|
+
## Serve it on your own machine
|
|
36
|
+
|
|
37
|
+
The same build runs on workerd, Cloudflare's open-source runtime, with no Cloudflare account. Set `ADMIN_TOKEN` and `SESSION_SECRET` in the environment, or in `.dev.vars`, then:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm run serve # builds, then serves on http://localhost:8787
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Every repo, person and job is kept in `.data/workerd`, so a restart keeps them. [Git on workerd](../../docs/deploy/workerd.md) says how to run it for good, and what it gives up beside Cloudflare.
|
|
44
|
+
|
|
37
45
|
## What's yours to change
|
|
38
46
|
|
|
39
47
|
| File | What it decides |
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
-- Better Auth 1.7.19's tables for the starter's options in src/signin/auth.ts: people by their login
|
|
2
2
|
-- (username), their password accounts, sessions with each one's sealed Git token, and the
|
|
3
|
-
-- rate limit's counts. Written by Better Auth's getMigrations from those options
|
|
4
|
-
--
|
|
3
|
+
-- rate limit's counts. Written by Better Auth's getMigrations from those options. The app applies
|
|
4
|
+
-- it, and each file here, itself, as src/signin/migrate.ts says.
|
|
5
5
|
create table "user" ("id" text not null primary key, "name" text not null, "email" text not null unique, "emailVerified" integer not null, "image" text, "createdAt" date not null, "updatedAt" date not null, "username" text unique);
|
|
6
6
|
|
|
7
7
|
create table "session" ("id" text not null primary key, "expiresAt" date not null, "token" text not null unique, "createdAt" date not null, "updatedAt" date not null, "ipAddress" text, "userAgent" text, "userId" text not null references "user" ("id") on delete cascade, "gitTokenId" text, "gitToken" text);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
-- person's passkeys, by the public key that checks them. Written by Better Auth's getMigrations
|
|
3
3
|
-- from those options, less 0001's tables. A credential ID is unique, since the plugin finds a
|
|
4
4
|
-- sign-in's passkey by it: the options' `unique-credential-id` plugin says so, and each dialect's
|
|
5
|
-
-- migration has it.
|
|
5
|
+
-- migration has it.
|
|
6
6
|
|
|
7
7
|
create table "passkey" ("id" text not null primary key, "name" text, "publicKey" text not null, "userId" text not null references "user" ("id") on delete cascade, "credentialID" text not null unique, "counter" integer not null, "deviceType" text not null, "backedUp" integer not null, "transports" text, "createdAt" date, "aaguid" text);
|
|
8
8
|
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
-- src/signin/auth.ts: orgs by their login (slug), their members, the invitations the starter
|
|
3
3
|
-- turns off, each session's active org, and owner_names, the one namespace people's logins and
|
|
4
4
|
-- orgs' slugs share (Q631). Written by Better Auth's getMigrations from those options over 0002.
|
|
5
|
-
-- Apply it with `wrangler d1 migrations apply AUTH_DB`, as 0001.
|
|
6
5
|
alter table "session" add column "activeOrganizationId" text;
|
|
7
6
|
|
|
8
7
|
create table "organization" ("id" text not null primary key, "name" text not null, "slug" text not null unique, "logo" text, "createdAt" date not null, "metadata" text);
|
|
@@ -2,5 +2,4 @@
|
|
|
2
2
|
-- an org's and a repo's picture in one table, each row under its kind and its owner's ID, as
|
|
3
3
|
-- `user:<id>`, `org:<id>` or `repo:<REST id>`, with its kind, sniffed type, bytes as base64, their
|
|
4
4
|
-- count and their SHA-256. Written by Better Auth's getMigrations from those options over 0003.
|
|
5
|
-
-- Apply it with `wrangler d1 migrations apply AUTH_DB`, as 0001.
|
|
6
5
|
create table "avatar" ("id" text not null primary key, "kind" text not null, "type" text not null, "bytes" text not null, "size" integer not null, "hash" text not null, "updatedAt" date not null);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
-- src/signin/auth.ts: one row a person and a repo, under the repo's internal ID and the person's row
|
|
3
3
|
-- ID, `<repo>:<userId>`, with the role and when it was first made. A person's delete takes their
|
|
4
4
|
-- grants, and Git's `repo.deleted` a repo's. Written by Better Auth's getMigrations from those
|
|
5
|
-
-- options over 0004.
|
|
5
|
+
-- options over 0004.
|
|
6
6
|
create table "repo_grant" ("id" text not null primary key, "repo" text not null, "userId" text not null references "user" ("id") on delete cascade, "role" text not null, "createdAt" date not null);
|
|
7
7
|
|
|
8
8
|
create index "repo_grant_repo_idx" on "repo_grant" ("repo");
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"dev": "vp dev",
|
|
16
16
|
"build": "vp build",
|
|
17
17
|
"deploy": "vp build && wrangler deploy",
|
|
18
|
+
"serve": "vp build && node scripts/serve.ts",
|
|
18
19
|
"generate": "openapi-typescript ../../packages/git/docs/openapi.json -o generated/git-rest.ts"
|
|
19
20
|
},
|
|
20
21
|
"dependencies": {
|
|
@@ -75,6 +76,7 @@
|
|
|
75
76
|
"tw-animate-css": "catalog:",
|
|
76
77
|
"typescript": "catalog:",
|
|
77
78
|
"vite-plus": "catalog:",
|
|
79
|
+
"workerd": "catalog:",
|
|
78
80
|
"wrangler": "catalog:"
|
|
79
81
|
}
|
|
80
82
|
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `npm run serve`: the app's build on workerd, Cloudflare's open-source runtime, on a machine of the
|
|
3
|
+
* host's own. `vp build` has written the Worker and the config Cloudflare's Vite plugin made for
|
|
4
|
+
* it; this reads that config, keeps what workerd takes, adds the app's secrets to its `vars`, writes
|
|
5
|
+
* it beside the plugin's, readable by its owner alone, and serves it:
|
|
6
|
+
*
|
|
7
|
+
* npm run serve # http://localhost:8787
|
|
8
|
+
* PORT=8080 WORKERD_DATA_DIR=/var/lib/git npm run serve
|
|
9
|
+
*
|
|
10
|
+
* The secrets come from the environment, or from `.dev.vars` where the environment lacks one.
|
|
11
|
+
* Every repo, person and job is in the data folder, `.data/workerd` unless `WORKERD_DATA_DIR`
|
|
12
|
+
* says, so a restart keeps them. `docs/deploy/workerd.md` says what a host gives up.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { createRequire } from 'node:module';
|
|
17
|
+
import { constants } from 'node:os';
|
|
18
|
+
import { resolve } from 'node:path';
|
|
19
|
+
import { argv, env, exit } from 'node:process';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { parseEnv } from 'node:util';
|
|
22
|
+
|
|
23
|
+
import * as Schema from 'effect/Schema';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The top-level keys workerd takes from a Wrangler config, as `workerd -h` lists them at the
|
|
27
|
+
* catalog's `workerd`, 1.20261202.1: it refuses any other. Of the plugin's, it drops `limits`, since
|
|
28
|
+
* workerd holds a Worker to no CPU limit, and `rules`, which workerd refuses.
|
|
29
|
+
*/
|
|
30
|
+
export const workerdKeys = [
|
|
31
|
+
'$schema',
|
|
32
|
+
'name',
|
|
33
|
+
'main',
|
|
34
|
+
'compatibility_date',
|
|
35
|
+
'compatibility_flags',
|
|
36
|
+
'vars',
|
|
37
|
+
'durable_objects',
|
|
38
|
+
'exports',
|
|
39
|
+
'migrations',
|
|
40
|
+
'no_bundle',
|
|
41
|
+
'kv_namespaces',
|
|
42
|
+
'r2_buckets',
|
|
43
|
+
'triggers',
|
|
44
|
+
'queues',
|
|
45
|
+
'workflows',
|
|
46
|
+
'd1_databases',
|
|
47
|
+
'secrets_store_secrets',
|
|
48
|
+
'ratelimits',
|
|
49
|
+
'assets',
|
|
50
|
+
] as const;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The app's secrets, which it needs, and the names it reads when they're set: Cloudflare's, as the
|
|
54
|
+
* app's `src/platform.ts` lists them. `init` copies no `platform.ts`, so this holds its own list,
|
|
55
|
+
* and `platform.test.ts` holds it to Cloudflare's.
|
|
56
|
+
*/
|
|
57
|
+
export const secretNames = ['ADMIN_TOKEN', 'SESSION_SECRET'] as const;
|
|
58
|
+
|
|
59
|
+
export const optionalNames = [
|
|
60
|
+
'SIGN_UP',
|
|
61
|
+
'IMAGE_PROXY',
|
|
62
|
+
'R2_ACCOUNT_ID',
|
|
63
|
+
'R2_ACCESS_KEY_ID',
|
|
64
|
+
'R2_SECRET_ACCESS_KEY',
|
|
65
|
+
'CLIENT_IP_HEADER',
|
|
66
|
+
] as const;
|
|
67
|
+
|
|
68
|
+
/** The port workerd serves on, unless `PORT` says. */
|
|
69
|
+
export const defaultPort = 8787;
|
|
70
|
+
|
|
71
|
+
/** Where workerd keeps its state, under the app's folder, unless `WORKERD_DATA_DIR` says. */
|
|
72
|
+
export const defaultDataDir = '.data/workerd';
|
|
73
|
+
|
|
74
|
+
const PluginConfig = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json));
|
|
75
|
+
|
|
76
|
+
const Vars = Schema.Record(Schema.String, Schema.Json);
|
|
77
|
+
|
|
78
|
+
const decodeConfig = Schema.decodeUnknownSync(PluginConfig);
|
|
79
|
+
|
|
80
|
+
const decodeVars = Schema.decodeUnknownSync(Vars);
|
|
81
|
+
|
|
82
|
+
/** What `serve` reads: the plugin's config, the environment, `.dev.vars` if there is one, the port. */
|
|
83
|
+
export interface ServeInput {
|
|
84
|
+
readonly config: string;
|
|
85
|
+
readonly environment: Readonly<Record<string, string | undefined>>;
|
|
86
|
+
readonly devVars: string | undefined;
|
|
87
|
+
readonly port: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The config workerd serves, as JSON: the plugin's keys workerd takes, as the plugin wrote them,
|
|
92
|
+
* and `vars` with each secret and each optional name that's set, from the environment over
|
|
93
|
+
* `.dev.vars`, and `APP_ORIGIN` where it's served, unless the environment sets it. It throws, naming
|
|
94
|
+
* each, when a secret is in neither.
|
|
95
|
+
*/
|
|
96
|
+
export const workerdConfig = (input: ServeInput) => {
|
|
97
|
+
const plugin = decodeConfig(input.config);
|
|
98
|
+
const file = input.devVars === undefined ? {} : parseEnv(input.devVars);
|
|
99
|
+
const valueOf = (name: string) => input.environment[name] ?? file[name];
|
|
100
|
+
|
|
101
|
+
const missing = secretNames.filter((name) => (valueOf(name) ?? '') === '');
|
|
102
|
+
if (missing.length > 0)
|
|
103
|
+
throw new Error(
|
|
104
|
+
`${missing.join(' and ')} ${missing.length === 1 ? "isn't" : "aren't"} set: set ${missing.length === 1 ? 'it' : 'each'} in the environment, or in .dev.vars`,
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
const set = [...secretNames, ...optionalNames].flatMap((name) => {
|
|
108
|
+
const value = valueOf(name);
|
|
109
|
+
|
|
110
|
+
return value === undefined ? [] : [[name, value] as const];
|
|
111
|
+
});
|
|
112
|
+
const vars = {
|
|
113
|
+
...decodeVars(plugin['vars'] ?? {}),
|
|
114
|
+
...Object.fromEntries(set),
|
|
115
|
+
// Always set, empty for none, so the Worker knows it's on workerd, where nothing sets
|
|
116
|
+
// `cf-connecting-ip` and a caller's own copy is trusted by nothing.
|
|
117
|
+
CLIENT_IP_HEADER: valueOf('CLIENT_IP_HEADER') ?? '',
|
|
118
|
+
APP_ORIGIN: input.environment['APP_ORIGIN'] ?? `http://localhost:${input.port}`,
|
|
119
|
+
};
|
|
120
|
+
const kept = workerdKeys.flatMap((key) =>
|
|
121
|
+
key === 'vars' || plugin[key] === undefined ? [] : [[key, plugin[key]] as const],
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
return `${JSON.stringify({ ...Object.fromEntries(kept), vars }, null, 2)}\n`;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/** `PORT` as a port, or the default. */
|
|
128
|
+
export const portOf = (text: string | undefined) => {
|
|
129
|
+
if (text === undefined || text === '') return defaultPort;
|
|
130
|
+
|
|
131
|
+
const port = Number(text);
|
|
132
|
+
if (!Number.isInteger(port) || port < 1 || port > 65_535)
|
|
133
|
+
throw new Error(`PORT is ${text}: a port is a whole number from 1 to 65535`);
|
|
134
|
+
|
|
135
|
+
return port;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Writes `text` at `path`, readable and writable by its owner alone, since it holds secrets: in a
|
|
140
|
+
* file of its own, made at that mode, so no reader of a file already there, at a wider one, sees it.
|
|
141
|
+
*/
|
|
142
|
+
export const writeSecret = (path: string, text: string) => {
|
|
143
|
+
rmSync(path, { force: true });
|
|
144
|
+
writeFileSync(path, text, { mode: 0o600, flag: 'wx' });
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Makes the data folder, or takes the one there, open to its owner alone: it holds every repo's
|
|
149
|
+
* packs, the people's password hashes and the webhooks' secrets.
|
|
150
|
+
*/
|
|
151
|
+
export const ownDataDir = (path: string) => {
|
|
152
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
153
|
+
chmodSync(path, 0o700);
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* What serve exits with once workerd has: its own code, or, for a signal, 0 when it's the one
|
|
158
|
+
* serve passed on, a stop someone asked for, and `128 + n` for any other, such as the OOM killer's
|
|
159
|
+
* SIGKILL, so a service manager's restart on failure starts it again.
|
|
160
|
+
*/
|
|
161
|
+
export const exitStatus = (
|
|
162
|
+
code: number | null,
|
|
163
|
+
signal: NodeJS.Signals | null,
|
|
164
|
+
passedOn: NodeJS.Signals | undefined,
|
|
165
|
+
): number => {
|
|
166
|
+
if (code !== null) return code;
|
|
167
|
+
|
|
168
|
+
if (signal === null) return 1;
|
|
169
|
+
|
|
170
|
+
return signal === passedOn ? 0 : 128 + constants.signals[signal];
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/** Builds the config from the app's folder `app`, writes it, and runs workerd on it. */
|
|
174
|
+
const serve = (app: string) => {
|
|
175
|
+
const plugin = resolve(app, 'dist/server/wrangler.json');
|
|
176
|
+
if (!existsSync(plugin)) throw new Error(`No build at ${plugin}: run \`vp build\` first`);
|
|
177
|
+
|
|
178
|
+
const devVars = resolve(app, '.dev.vars');
|
|
179
|
+
const port = portOf(env['PORT']);
|
|
180
|
+
const config = resolve(app, 'dist/server/workerd.json');
|
|
181
|
+
writeSecret(
|
|
182
|
+
config,
|
|
183
|
+
workerdConfig({
|
|
184
|
+
config: readFileSync(plugin, 'utf8'),
|
|
185
|
+
environment: env,
|
|
186
|
+
devVars: existsSync(devVars) ? readFileSync(devVars, 'utf8') : undefined,
|
|
187
|
+
port,
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const workerd = createRequire(import.meta.url).resolve('workerd/bin/workerd');
|
|
192
|
+
const data = resolve(app, env['WORKERD_DATA_DIR'] ?? defaultDataDir);
|
|
193
|
+
ownDataDir(data);
|
|
194
|
+
const child = spawn(
|
|
195
|
+
workerd,
|
|
196
|
+
['serve', '--experimental', config, '--socket-addr', `http=*:${port}`, '--data-dir', data],
|
|
197
|
+
{ cwd: app, stdio: 'inherit' },
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
let passedOn: NodeJS.Signals | undefined;
|
|
201
|
+
|
|
202
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
203
|
+
process.on(signal, () => {
|
|
204
|
+
passedOn = signal;
|
|
205
|
+
child.kill(signal);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
child.on('exit', (code, signal) => exit(exitStatus(code, signal, passedOn)));
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
if (argv[1] === fileURLToPath(import.meta.url)) {
|
|
213
|
+
try {
|
|
214
|
+
serve(fileURLToPath(new URL('..', import.meta.url)));
|
|
215
|
+
} catch (error) {
|
|
216
|
+
console.error(error instanceof Error ? error.message : error);
|
|
217
|
+
exit(1);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -13,6 +13,7 @@ import { hostRules } from './policy.ts';
|
|
|
13
13
|
import { shownRules } from './settings/rules.ts';
|
|
14
14
|
import { deviceAttemptAnswer, deviceAttemptGate } from './signin/attempts.ts';
|
|
15
15
|
import { sessionCookieOf, sessionEnder, sessionFrom, sessionIdFrom } from './signin/auth.ts';
|
|
16
|
+
import { servedClientIp } from './signin/client-ip.ts';
|
|
16
17
|
import { withoutHostSession } from './signin/host-session.ts';
|
|
17
18
|
|
|
18
19
|
export { Jobs, Records } from './git.ts';
|
|
@@ -96,8 +97,9 @@ const seeded = () => {
|
|
|
96
97
|
export default createServerEntry({
|
|
97
98
|
fetch: images.around(async (incoming) => {
|
|
98
99
|
// A host session is the app's server's to set in this Worker, never a caller's to send
|
|
99
|
-
// (Q520): every route, the APIs, the app and any upgrade, sees the request without one.
|
|
100
|
-
|
|
100
|
+
// (Q520): every route, the APIs, the app and any upgrade, sees the request without one. On
|
|
101
|
+
// workerd, the caller's address is the host's proxy's to name, never the caller's.
|
|
102
|
+
const request = withoutHostSession(servedClientIp(incoming, env.CLIENT_IP_HEADER));
|
|
101
103
|
if (__DEV_SEED__) await seeded();
|
|
102
104
|
|
|
103
105
|
const answered = await owned(request);
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
isTaken,
|
|
31
31
|
ownerNames,
|
|
32
32
|
} from './owner-names.ts';
|
|
33
|
+
import { migrate } from './migrate.ts';
|
|
33
34
|
import { revokeRetrying } from './revoke.ts';
|
|
34
35
|
import { open, seal } from './seal.ts';
|
|
35
36
|
import { avatarTable, avatars } from './avatars.ts';
|
|
@@ -65,6 +66,12 @@ export interface NodeSqliteDatabase {
|
|
|
65
66
|
*/
|
|
66
67
|
export type AuthDatabase = D1Database | NodeSqliteDatabase | DialectDatabase;
|
|
67
68
|
|
|
69
|
+
/** Whether `database` is D1's binding, which alone of the three has `batch`, as Better Auth tells it. */
|
|
70
|
+
const isD1 = (database: AuthDatabase): database is D1Database => 'batch' in database;
|
|
71
|
+
|
|
72
|
+
/** Each instance's database, as `starterAuth` made it over, for `readyAuth` to ready. */
|
|
73
|
+
const databases = new WeakMap<Auth, AuthDatabase>();
|
|
74
|
+
|
|
68
75
|
/** What the app's people need: their database, the session secret, where it's served, and Git's tokens. */
|
|
69
76
|
export interface StarterAuthOptions {
|
|
70
77
|
/** Better Auth's tables, which `migrations/sql/` makes in D1. */
|
|
@@ -86,8 +93,9 @@ export interface StarterAuthOptions {
|
|
|
86
93
|
readonly ownsRepos: (login: string) => Effect.Effect<boolean>;
|
|
87
94
|
/**
|
|
88
95
|
* The header Better Auth keys its rate limits on, which only the platform sets: Cloudflare's
|
|
89
|
-
* `cf-connecting-ip`,
|
|
90
|
-
* address after dropping any copy the
|
|
96
|
+
* `cf-connecting-ip`, which on workerd `servedClientIp` sets in its place, or on Node
|
|
97
|
+
* `clientIpHeader`, which the server sets from the caller's address after dropping any copy the
|
|
98
|
+
* caller sent.
|
|
91
99
|
*/
|
|
92
100
|
readonly ipHeader: string;
|
|
93
101
|
}
|
|
@@ -143,9 +151,15 @@ const refuseLogin = (login: string) => {
|
|
|
143
151
|
throw new APIError('BAD_REQUEST', { code, message: problem });
|
|
144
152
|
};
|
|
145
153
|
|
|
146
|
-
/**
|
|
154
|
+
/** An IP address as a URL's hostname writes it: dotted IPv4, or IPv6 in brackets. */
|
|
155
|
+
const ipHostname = /^(\d+\.){3}\d+$|^\[.*\]$/;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The email Better Auth asks every person for, which reaches no one: the login's, at the host, or
|
|
159
|
+
* at `localhost` on a host served at an IP address, whose email Better Auth refuses as invalid.
|
|
160
|
+
*/
|
|
147
161
|
const hiddenEmail = (login: string, hostname: string) =>
|
|
148
|
-
`${login.toLowerCase()}@users.noreply.${hostname}`;
|
|
162
|
+
`${login.toLowerCase()}@users.noreply.${ipHostname.test(hostname) ? 'localhost' : hostname}`;
|
|
149
163
|
|
|
150
164
|
/** The name a person goes by: the one they gave, or their login when they left it empty. */
|
|
151
165
|
const named = (login: string, name: string | undefined) =>
|
|
@@ -472,6 +486,8 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
|
|
|
472
486
|
// On, whatever `NODE_ENV` says: Better Auth turns both off under `test`.
|
|
473
487
|
disableOriginCheck: false,
|
|
474
488
|
disableCSRFCheck: false,
|
|
489
|
+
// On D1, `readyAuth` applies the app's migrations in place of Better Auth's check.
|
|
490
|
+
database: { validateSchema: !isD1(options.database) },
|
|
475
491
|
},
|
|
476
492
|
hooks: {
|
|
477
493
|
before: createAuthMiddleware(async (ctx) => {
|
|
@@ -636,6 +652,8 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
|
|
|
636
652
|
/** Better Auth's adapter, which the organization plugin's hooks, given no context, read through. */
|
|
637
653
|
const adapterOf = async (): Promise<DBAdapter> => (await auth.$context).adapter;
|
|
638
654
|
|
|
655
|
+
databases.set(auth, options.database);
|
|
656
|
+
|
|
639
657
|
return auth;
|
|
640
658
|
};
|
|
641
659
|
|
|
@@ -646,8 +664,9 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
|
|
|
646
664
|
export type StarterAuth = Auth;
|
|
647
665
|
|
|
648
666
|
/**
|
|
649
|
-
* Better Auth's adapter, once its schema check has settled
|
|
650
|
-
*
|
|
667
|
+
* Better Auth's adapter, once its schema check has settled, where it has one: on D1 it has none,
|
|
668
|
+
* since `readyAuth` applies the app's migrations instead. Making Better Auth starts the check, and
|
|
669
|
+
* its own routes await it, so only a read of `$context` alone needs this.
|
|
651
670
|
*/
|
|
652
671
|
export const readyAdapter = async (auth: StarterAuth): Promise<DBAdapter> => {
|
|
653
672
|
const context = await auth.$context;
|
|
@@ -658,13 +677,16 @@ export const readyAdapter = async (auth: StarterAuth): Promise<DBAdapter> => {
|
|
|
658
677
|
|
|
659
678
|
/**
|
|
660
679
|
* Better Auth for a request: the isolate's, kept once a request's check of it has settled, or else
|
|
661
|
-
* one `make` makes for this request, which awaits its own check
|
|
662
|
-
*
|
|
663
|
-
*
|
|
680
|
+
* one `make` makes for this request, which awaits its own check: on D1, the app's migrations,
|
|
681
|
+
* applied as `migrate` applies them, and elsewhere Better Auth's schema check. A Worker settles a
|
|
682
|
+
* promise only in the request that made it, so no request awaits another's check: one that ended
|
|
683
|
+
* first, by a disconnect or an early answer, would leave it unsettled, and every later sign-in
|
|
684
|
+
* with it (#480).
|
|
664
685
|
*
|
|
665
|
-
* So requests that arrive together, before any is kept, each make an instance and run its
|
|
666
|
-
*
|
|
667
|
-
*
|
|
686
|
+
* So requests that arrive together, before any is kept, each make an instance and run its check,
|
|
687
|
+
* and only the first to settle is kept. That's the cost of sharing no promise, and it's bounded by
|
|
688
|
+
* how many requests arrive in that window: once one is kept, no request makes another. A check
|
|
689
|
+
* that fails fails its request, keeps nothing, and the next request runs it again.
|
|
668
690
|
*/
|
|
669
691
|
export const readyAuth = (make: () => StarterAuth): (() => Promise<StarterAuth>) => {
|
|
670
692
|
let ready: StarterAuth | undefined;
|
|
@@ -673,6 +695,9 @@ export const readyAuth = (make: () => StarterAuth): (() => Promise<StarterAuth>)
|
|
|
673
695
|
if (ready !== undefined) return ready;
|
|
674
696
|
|
|
675
697
|
const made = make();
|
|
698
|
+
const database = databases.get(made);
|
|
699
|
+
if (database !== undefined && isD1(database)) await migrate(database);
|
|
700
|
+
|
|
676
701
|
await readyAdapter(made);
|
|
677
702
|
ready ??= made;
|
|
678
703
|
|
|
@@ -20,20 +20,35 @@ const proxied = (proxyHeader: string, value: string) =>
|
|
|
20
20
|
(proxyHeader === 'x-forwarded-for' ? (value.split(',').at(-1) ?? '') : value).trim();
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
|
-
* `incoming` with the caller's address in `
|
|
24
|
-
* the socket's address, unless `proxyHeader` names the header the proxy in
|
|
25
|
-
* `x-real-ip`, which only a proxy that overwrites it makes trustworthy. A
|
|
26
|
-
* header is missing or empty keeps the socket's address, the proxy's own
|
|
23
|
+
* `incoming` with the caller's address in `target`, `clientIpHeader` unless given, and none the
|
|
24
|
+
* caller sent there. It's the socket's address, unless `proxyHeader` names the header the proxy in
|
|
25
|
+
* front sets, such as `x-real-ip`, which only a proxy that overwrites it makes trustworthy. A
|
|
26
|
+
* request whose proxy header is missing or empty keeps the socket's address, the proxy's own, and
|
|
27
|
+
* one with neither, as on workerd, which gives no socket's, carries none.
|
|
27
28
|
*/
|
|
28
|
-
export const withClientIp = (
|
|
29
|
+
export const withClientIp = (
|
|
30
|
+
incoming: Request & Located,
|
|
31
|
+
proxyHeader: string | undefined,
|
|
32
|
+
target: string = clientIpHeader,
|
|
33
|
+
) => {
|
|
29
34
|
const headers = new Headers(incoming.headers);
|
|
30
|
-
headers.delete(
|
|
35
|
+
headers.delete(target);
|
|
31
36
|
|
|
32
37
|
const named =
|
|
33
38
|
proxyHeader === undefined || proxyHeader === '' ? undefined : proxyHeader.toLowerCase();
|
|
34
39
|
const sent = named === undefined ? '' : proxied(named, incoming.headers.get(named) ?? '');
|
|
35
40
|
const address = sent === '' ? incoming.ip : sent;
|
|
36
|
-
if (address !== undefined && address !== '') headers.set(
|
|
41
|
+
if (address !== undefined && address !== '') headers.set(target, address);
|
|
37
42
|
|
|
38
43
|
return withHeaders(incoming, headers);
|
|
39
44
|
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The caller's address in `cf-connecting-ip`, the header the Worker's limits key on, as `npm run
|
|
48
|
+
* serve` runs it on workerd, which sets none: there `proxyHeader` is the host's `CLIENT_IP_HEADER`,
|
|
49
|
+
* the header its proxy sets, or empty for none, and the caller's own copy goes, so with none every
|
|
50
|
+
* caller shares one bucket rather than naming its own. On Cloudflare, which sets the header itself
|
|
51
|
+
* in place of any the caller sent, `proxyHeader` is unset and `incoming` is kept as it is.
|
|
52
|
+
*/
|
|
53
|
+
export const servedClientIp = (incoming: Request, proxyHeader: string | undefined) =>
|
|
54
|
+
proxyHeader === undefined ? incoming : withClientIp(incoming, proxyHeader, 'cf-connecting-ip');
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/// <reference types="vite-plus/client" />
|
|
2
|
+
import type { D1Database } from '@cloudflare/workers-types';
|
|
3
|
+
import * as Schema from 'effect/Schema';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The app's own tables in D1: `migrations/sql/`'s files, applied by the app itself before sign-in's
|
|
7
|
+
* first use in each isolate, so no host runs `wrangler d1 migrations apply`, on Cloudflare or on
|
|
8
|
+
* workerd, whose data folder wrangler can't reach.
|
|
9
|
+
*
|
|
10
|
+
* Each file applied is recorded by name in wrangler's own `d1_migrations` table, made as wrangler
|
|
11
|
+
* makes it, so a database wrangler migrated is already up to date, and wrangler finds nothing to
|
|
12
|
+
* apply to one the app migrated. A file applies as one D1 batch, its statements and then its
|
|
13
|
+
* record, so it lands whole or not at all. Two isolates may race to apply one file: the record's
|
|
14
|
+
* unique name fails the loser's batch whole, even where its statements could run twice, and the
|
|
15
|
+
* loser reads the record again and finds the file applied. A batch that fails with no record is a
|
|
16
|
+
* real failure: it fails the request, nothing is kept, and the next request tries again.
|
|
17
|
+
* `verification/D1Migrate.tla` checks every file is applied exactly once and recorded, however two
|
|
18
|
+
* isolates interleave.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** One migration: its file's name, as wrangler records it, and its SQL. */
|
|
22
|
+
export interface Migration {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly sql: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The most migrations the app holds, the bound on the migrator's loop and on its one read of the
|
|
29
|
+
* record, which binds each file's name: D1 binds at most 100 parameters a statement. Five today.
|
|
30
|
+
*/
|
|
31
|
+
export const migrationsMost = 100;
|
|
32
|
+
|
|
33
|
+
/** `migrations/sql/`'s files, built in, so the app needs no file system to read them, by name. */
|
|
34
|
+
const files: Readonly<Record<string, string>> = import.meta.glob('../../migrations/sql/*.sql', {
|
|
35
|
+
query: '?raw',
|
|
36
|
+
import: 'default',
|
|
37
|
+
eager: true,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** The app's migrations, in name order, as wrangler applies them. */
|
|
41
|
+
export const migrations: readonly Migration[] = Object.entries(files)
|
|
42
|
+
.map(([path, sql]) => ({ name: path.slice(path.lastIndexOf('/') + 1), sql }))
|
|
43
|
+
.toSorted((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
44
|
+
|
|
45
|
+
/** Wrangler's record of the files applied, as `wrangler d1 migrations apply` makes it. */
|
|
46
|
+
const records = `CREATE TABLE IF NOT EXISTS "d1_migrations"(
|
|
47
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
48
|
+
name TEXT UNIQUE,
|
|
49
|
+
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
|
50
|
+
);`;
|
|
51
|
+
|
|
52
|
+
const appliedOf = (database: D1Database, of: readonly Migration[]) =>
|
|
53
|
+
database
|
|
54
|
+
.prepare(`SELECT name FROM d1_migrations WHERE name IN (${of.map(() => '?').join(', ')})`)
|
|
55
|
+
.bind(...of.map((each) => each.name));
|
|
56
|
+
|
|
57
|
+
const decodeNames = /* @__PURE__ */ Schema.decodeUnknownSync(
|
|
58
|
+
Schema.Array(Schema.Struct({ name: Schema.String })),
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
/** The names a read of the record found. */
|
|
62
|
+
const namesIn = (rows: readonly object[]) => new Set(decodeNames(rows).map((row) => row.name));
|
|
63
|
+
|
|
64
|
+
/** Applies one file and its record as one batch, or finds another isolate's record of it. */
|
|
65
|
+
const apply = async (database: D1Database, migration: Migration) => {
|
|
66
|
+
const statements = [
|
|
67
|
+
...statementsOf(migration.sql),
|
|
68
|
+
`INSERT INTO d1_migrations (name) VALUES ('${migration.name.replaceAll("'", "''")}')`,
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
await database.batch(statements.map((statement) => database.prepare(statement)));
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const found = await appliedOf(database, [migration]).all<object>();
|
|
75
|
+
if (namesIn(found.results).has(migration.name)) return;
|
|
76
|
+
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Applies to `database` each of `of`, the app's migrations unless a test names others, that its
|
|
83
|
+
* record lacks, in order, each with its record. The record is made and read in one batch, so a
|
|
84
|
+
* database already up to date costs one round trip.
|
|
85
|
+
*/
|
|
86
|
+
export const migrate = async (database: D1Database, of: readonly Migration[] = migrations) => {
|
|
87
|
+
if (of.length === 0) return;
|
|
88
|
+
|
|
89
|
+
if (of.length > migrationsMost)
|
|
90
|
+
throw new Error(`The app holds ${of.length} migrations, past its ${migrationsMost}`);
|
|
91
|
+
|
|
92
|
+
const [, read] = await database.batch<object>([
|
|
93
|
+
database.prepare(records),
|
|
94
|
+
appliedOf(database, of),
|
|
95
|
+
]);
|
|
96
|
+
const applied = namesIn(read?.results ?? []);
|
|
97
|
+
|
|
98
|
+
for (const migration of of) if (!applied.has(migration.name)) await apply(database, migration);
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** A token of SQLite's `sqlite3_complete`, which tells where a statement ends. */
|
|
102
|
+
type Token = 'semi' | 'space' | 'other' | 'explain' | 'create' | 'temp' | 'trigger' | 'end';
|
|
103
|
+
|
|
104
|
+
/** Where `sqlite3_complete` is in a statement: a trigger's body ends only at `END;`. */
|
|
105
|
+
type State = 'invalid' | 'start' | 'normal' | 'explain' | 'create' | 'trigger' | 'semi' | 'end';
|
|
106
|
+
|
|
107
|
+
const allOther = (to: State) => ({
|
|
108
|
+
semi: to,
|
|
109
|
+
space: to,
|
|
110
|
+
other: to,
|
|
111
|
+
explain: to,
|
|
112
|
+
create: to,
|
|
113
|
+
temp: to,
|
|
114
|
+
trigger: to,
|
|
115
|
+
end: to,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
/** `sqlite3_complete`'s transitions, as wrangler's splitter takes them. */
|
|
119
|
+
const transitions: Readonly<Record<State, Readonly<Record<Token, State>>>> = {
|
|
120
|
+
invalid: {
|
|
121
|
+
...allOther('normal'),
|
|
122
|
+
semi: 'start',
|
|
123
|
+
space: 'invalid',
|
|
124
|
+
explain: 'explain',
|
|
125
|
+
create: 'create',
|
|
126
|
+
},
|
|
127
|
+
start: {
|
|
128
|
+
...allOther('normal'),
|
|
129
|
+
semi: 'start',
|
|
130
|
+
space: 'start',
|
|
131
|
+
explain: 'explain',
|
|
132
|
+
create: 'create',
|
|
133
|
+
},
|
|
134
|
+
normal: { ...allOther('normal'), semi: 'start' },
|
|
135
|
+
explain: {
|
|
136
|
+
...allOther('normal'),
|
|
137
|
+
semi: 'start',
|
|
138
|
+
space: 'explain',
|
|
139
|
+
other: 'explain',
|
|
140
|
+
create: 'create',
|
|
141
|
+
},
|
|
142
|
+
create: {
|
|
143
|
+
...allOther('normal'),
|
|
144
|
+
semi: 'start',
|
|
145
|
+
space: 'create',
|
|
146
|
+
temp: 'create',
|
|
147
|
+
trigger: 'trigger',
|
|
148
|
+
},
|
|
149
|
+
trigger: { ...allOther('trigger'), semi: 'semi' },
|
|
150
|
+
semi: { ...allOther('trigger'), semi: 'semi', space: 'semi', end: 'end' },
|
|
151
|
+
end: { ...allOther('trigger'), semi: 'start', space: 'end' },
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const keywords = new Map<string, Token>([
|
|
155
|
+
['explain', 'explain'],
|
|
156
|
+
['create', 'create'],
|
|
157
|
+
['temp', 'temp'],
|
|
158
|
+
['temporary', 'temp'],
|
|
159
|
+
['trigger', 'trigger'],
|
|
160
|
+
['end', 'end'],
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
const identifierChar = /[A-Za-z0-9_$\u0080-]/;
|
|
164
|
+
|
|
165
|
+
/** What closes each quote: a string's, an identifier's and SQLite's two others. */
|
|
166
|
+
const closers = new Map([
|
|
167
|
+
["'", "'"],
|
|
168
|
+
['"', '"'],
|
|
169
|
+
['`', '`'],
|
|
170
|
+
['[', ']'],
|
|
171
|
+
]);
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Where the statement from `start` ends, past its `;`, and whether it holds more than space,
|
|
175
|
+
* comments and semicolons. An unclosed quote or comment leaves it open, to the end.
|
|
176
|
+
*/
|
|
177
|
+
const statementEnd = (sql: string, start: number) => {
|
|
178
|
+
let state: State = 'invalid';
|
|
179
|
+
let useful = false;
|
|
180
|
+
|
|
181
|
+
for (let at = start; at < sql.length; at++) {
|
|
182
|
+
const char = sql[at] ?? '';
|
|
183
|
+
let token: Token;
|
|
184
|
+
if (char === ';') token = 'semi';
|
|
185
|
+
else if (' \r\t\n\f'.includes(char)) token = 'space';
|
|
186
|
+
else if (char === '/' && sql[at + 1] === '*') {
|
|
187
|
+
const close = sql.indexOf('*/', at + 2);
|
|
188
|
+
if (close === -1) return { end: undefined, useful };
|
|
189
|
+
|
|
190
|
+
at = close + 1;
|
|
191
|
+
token = 'space';
|
|
192
|
+
} else if (char === '-' && sql[at + 1] === '-') {
|
|
193
|
+
const close = sql.indexOf('\n', at + 2);
|
|
194
|
+
if (close === -1) return { end: undefined, useful };
|
|
195
|
+
|
|
196
|
+
at = close;
|
|
197
|
+
token = 'space';
|
|
198
|
+
} else if (closers.has(char)) {
|
|
199
|
+
const close = sql.indexOf(closers.get(char) ?? char, at + 1);
|
|
200
|
+
if (close === -1) return { end: undefined, useful: true };
|
|
201
|
+
|
|
202
|
+
at = close;
|
|
203
|
+
token = 'other';
|
|
204
|
+
} else if (identifierChar.test(char)) {
|
|
205
|
+
const from = at;
|
|
206
|
+
|
|
207
|
+
while (at + 1 < sql.length && identifierChar.test(sql[at + 1] ?? '')) at++;
|
|
208
|
+
|
|
209
|
+
token = keywords.get(sql.slice(from, at + 1).toLowerCase()) ?? 'other';
|
|
210
|
+
} else token = 'other';
|
|
211
|
+
|
|
212
|
+
useful ||= token !== 'semi' && token !== 'space';
|
|
213
|
+
state = transitions[state][token];
|
|
214
|
+
|
|
215
|
+
if (state === 'start') return { end: at + 1, useful };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return { end: undefined, useful };
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* A migration file's statements, each without its `;`, cut as wrangler's `splitSqlQuery` cuts a
|
|
223
|
+
* file that holds no transaction: at each `;` outside a quote, a comment or a trigger's body, by
|
|
224
|
+
* SQLite's own `sqlite3_complete`. One prepared statement can't hold a whole file, so a batch
|
|
225
|
+
* holds each. Its tests check it agrees with wrangler's.
|
|
226
|
+
*/
|
|
227
|
+
export const statementsOf = (sql: string): string[] => {
|
|
228
|
+
const trimmed = sql.trimEnd();
|
|
229
|
+
const semi = trimmed.indexOf(';');
|
|
230
|
+
if (semi === -1 || semi === trimmed.length - 1) return [sql];
|
|
231
|
+
|
|
232
|
+
const statements: string[] = [];
|
|
233
|
+
let start = 0;
|
|
234
|
+
|
|
235
|
+
while (start < sql.length) {
|
|
236
|
+
const { end, useful } = statementEnd(sql, start);
|
|
237
|
+
|
|
238
|
+
if (end === undefined) {
|
|
239
|
+
if (useful) statements.push(sql.slice(start).trim());
|
|
240
|
+
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const statement = sql.slice(start, end - 1).trim();
|
|
245
|
+
if (useful && statement.length > 0) statements.push(statement);
|
|
246
|
+
|
|
247
|
+
start = end;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return statements.length === 0 ? [sql] : statements;
|
|
251
|
+
};
|
package/app/pnpm-workspace.yaml
CHANGED
|
@@ -204,6 +204,10 @@ catalog:
|
|
|
204
204
|
yaml: 2.9.1
|
|
205
205
|
# Runs @ref0/infra/cloudflare's objects in workerd for its tests, through `createTestHarness`.
|
|
206
206
|
wrangler: 4.168.0
|
|
207
|
+
# The runtime the app's `npm run serve` runs its build on, a host's own machine: at least
|
|
208
|
+
# 1.20261202.1, since wrangler 4.168.0's own, 1.20261123.1, refuses `r2_buckets` under a Wrangler
|
|
209
|
+
# config. Apache-2.0.
|
|
210
|
+
workerd: 1.20261202.1
|
|
207
211
|
|
|
208
212
|
# Vite+ is Vite here: Vitest, which Vite+ bundles, asks for Vite as its peer, and gets Vite+'s core.
|
|
209
213
|
overrides:
|
|
@@ -222,3 +226,9 @@ allowBuilds:
|
|
|
222
226
|
|
|
223
227
|
minimumReleaseAgeExclude:
|
|
224
228
|
- '@ref0/workspace@0.17.0'
|
|
229
|
+
- '@cloudflare/workerd-darwin-64@1.20261202.1'
|
|
230
|
+
- '@cloudflare/workerd-darwin-arm64@1.20261202.1'
|
|
231
|
+
- '@cloudflare/workerd-linux-64@1.20261202.1'
|
|
232
|
+
- '@cloudflare/workerd-linux-arm64@1.20261202.1'
|
|
233
|
+
- '@cloudflare/workerd-windows-64@1.20261202.1'
|
|
234
|
+
- workerd@1.20261202.1
|
package/dist/cli/setup.mjs
CHANGED
|
@@ -1610,7 +1610,7 @@ const setupCommands = [init, Command.make("doctor", {
|
|
|
1610
1610
|
]],
|
|
1611
1611
|
stdinFrom: "ADMIN_TOKEN"
|
|
1612
1612
|
} : {
|
|
1613
|
-
says: platformOf(project.detected) === "node" ? starter !== void 0 ? `Build it with \`${project.packageManager.value} run build\`, start it with ${starter.start(project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : routed(project.framework) ? `Build it with \`${project.packageManager.value} run build\`, start it with ${routedStart(project.framework, project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : project.layout.kind === "mount" ? `Start your server with \`node --env-file-if-exists=.env\`, which loads what src/git.ts reads, ${signIn}, then push a scratch repo through it` : `Start it with \`${project.packageManager.value} start\`, ${project.held?.app === "ref0" ? "sign up on it, setting APP_ORIGIN to where it's served first" : signIn}, then push a scratch repo through it` : vercel ? `Check Production has each variable with \`vercel env ls production\`, deploy it with Vercel's CLI or a Git import, ${signIn}, then push a scratch repo through it` : `Set APP_ORIGIN to where it's served, make AUTH_DB
|
|
1613
|
+
says: platformOf(project.detected) === "node" ? starter !== void 0 ? `Build it with \`${project.packageManager.value} run build\`, start it with ${starter.start(project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : routed(project.framework) ? `Build it with \`${project.packageManager.value} run build\`, start it with ${routedStart(project.framework, project.packageManager.value)}, ${signIn}, then push a scratch repo through it` : project.layout.kind === "mount" ? `Start your server with \`node --env-file-if-exists=.env\`, which loads what src/git.ts reads, ${signIn}, then push a scratch repo through it` : `Start it with \`${project.packageManager.value} start\`, ${project.held?.app === "ref0" ? "sign up on it, setting APP_ORIGIN to where it's served first" : signIn}, then push a scratch repo through it` : vercel ? `Check Production has each variable with \`vercel env ls production\`, deploy it with Vercel's CLI or a Git import, ${signIn}, then push a scratch repo through it` : `Set APP_ORIGIN to where it's served, make AUTH_DB with \`wrangler d1 create\`, deploy it with \`wrangler deploy\`, set ${secretsOf(withDefaults(project.held ?? {}, project.project)).join(" and ")} with \`wrangler secret put\`, ${signIn}, then push a scratch repo through it`,
|
|
1614
1614
|
run: [[
|
|
1615
1615
|
"login",
|
|
1616
1616
|
`${served ?? "<host>"}${base}`,
|
package/dist/init/app.mjs
CHANGED
|
@@ -241,7 +241,8 @@ const appOutput = (choices, name, source, secret, vendor) => {
|
|
|
241
241
|
merge: (current) => ignoring(current, [
|
|
242
242
|
"node_modules",
|
|
243
243
|
".wrangler",
|
|
244
|
-
"dist"
|
|
244
|
+
"dist",
|
|
245
|
+
".data"
|
|
245
246
|
], secretFiles)
|
|
246
247
|
}
|
|
247
248
|
],
|
|
@@ -249,7 +250,7 @@ const appOutput = (choices, name, source, secret, vendor) => {
|
|
|
249
250
|
needs: [],
|
|
250
251
|
packages: appPackages.map((each) => `@ref0/${each}`),
|
|
251
252
|
secret: `${listed(made)}, made for wrangler dev, in .dev.vars`,
|
|
252
|
-
next: "
|
|
253
|
+
next: "Check it, then deploy it, or serve it on workerd with `npm run serve`"
|
|
253
254
|
};
|
|
254
255
|
};
|
|
255
256
|
export { appEnvModule, appGitModule, appManifest, appOutput, appPackages, appWrangler, checkedManifest, copied, entered };
|
package/dist/init/metadata.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/init/metadata.ts
|
|
2
2
|
/** The version `ref0-git`, `create-ref0-git` and Git's packages release at, all at once (Q738). */
|
|
3
|
-
const release = "0.
|
|
3
|
+
const release = "0.26.0";
|
|
4
4
|
/** The packages the app depends on, by their folder in a checkout's `packages/`. */
|
|
5
5
|
const appPackages = [
|
|
6
6
|
"infra",
|
package/dist/init/node-app.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import * as Redacted from "effect/Redacted";
|
|
|
15
15
|
/** Where `npm start` serves the app, the one origin Better Auth takes a POST from until it's set. */
|
|
16
16
|
const startOrigin = "http://localhost:3000";
|
|
17
17
|
/** The app's own files on Cloudflare that Node writes instead, or leaves out. */
|
|
18
|
-
const cloudflareOnly = /^(README\.md|vite\.config\.ts|src\/server\.ts|tsconfig\.worker\.json|\.dev\.vars\.example|migrations
|
|
18
|
+
const cloudflareOnly = /^(README\.md|vite\.config\.ts|src\/server\.ts|tsconfig\.worker\.json|\.dev\.vars\.example|migrations\/.*|scripts\/serve\.ts)$/;
|
|
19
19
|
/** Where each `--records` keeps the app's people, for the README. */
|
|
20
20
|
const peopleIn = {
|
|
21
21
|
sqlite: "`.data/auth.db`, a SQLite file",
|
|
@@ -79,7 +79,11 @@ const manifestOn = (choices) => {
|
|
|
79
79
|
start: "node --env-file-if-exists=.env .output/server/index.mjs",
|
|
80
80
|
migrate: "node --env-file-if-exists=.env scripts/migrate.ts"
|
|
81
81
|
},
|
|
82
|
-
dropped: [
|
|
82
|
+
dropped: [
|
|
83
|
+
"@cloudflare/vite-plugin",
|
|
84
|
+
"wrangler",
|
|
85
|
+
"workerd"
|
|
86
|
+
],
|
|
83
87
|
dependencies: {
|
|
84
88
|
nitro: nodeAppPackages.nitro,
|
|
85
89
|
...Object.fromEntries(parts.flatMap((part) => part.dependencies)),
|
package/dist/init/templates.mjs
CHANGED
|
@@ -136,7 +136,7 @@ var templates_default = {
|
|
|
136
136
|
"slot": "bucket",
|
|
137
137
|
"text": " /** The packs' bucket, and its name, which a signed link names. */\n readonly PACKS: R2Bucket;\n readonly PACKS_BUCKET: string;\n"
|
|
138
138
|
},
|
|
139
|
-
" /** People and their sessions: Better Auth's tables, which `migrations/sql/` makes. */\n readonly AUTH_DB: D1Database;\n /** Signs in as the admin, who makes repos and tokens and never pushes, and vouches at sign-in. */\n readonly ADMIN_TOKEN: string;\n /** At least 32 characters: what signs Better Auth's cookie, and seals each session's Git token. */\n readonly SESSION_SECRET: string;\n /** Where the app is served, such as `https://git.example.com`: Better Auth takes POSTs from it. */\n readonly APP_ORIGIN: string;\n /** `closed` turns sign-up off, so only the people already signed up sign in. Open when unset. */\n readonly SIGN_UP?: string;\n /** `off` turns the image proxy off, so a text's remote images load from their own origin (Q860). */\n readonly IMAGE_PROXY?: string;\n",
|
|
139
|
+
" /** People and their sessions: Better Auth's tables, which `migrations/sql/` makes. */\n readonly AUTH_DB: D1Database;\n /** Signs in as the admin, who makes repos and tokens and never pushes, and vouches at sign-in. */\n readonly ADMIN_TOKEN: string;\n /** At least 32 characters: what signs Better Auth's cookie, and seals each session's Git token. */\n readonly SESSION_SECRET: string;\n /** Where the app is served, such as `https://git.example.com`: Better Auth takes POSTs from it. */\n readonly APP_ORIGIN: string;\n /** `closed` turns sign-up off, so only the people already signed up sign in. Open when unset. */\n readonly SIGN_UP?: string;\n /** `off` turns the image proxy off, so a text's remote images load from their own origin (Q860). */\n readonly IMAGE_PROXY?: string;\n /**\n * Set by `npm run serve` alone, never on Cloudflare: the header the proxy in front of workerd\n * sets with the caller's address, such as `x-real-ip`, or empty for none, when every caller shares\n * one bucket of each limit. Set at all, the caller's own `cf-connecting-ip` counts for nothing.\n */\n readonly CLIENT_IP_HEADER?: string;\n",
|
|
140
140
|
{
|
|
141
141
|
"slot": "signing",
|
|
142
142
|
"text": " /** R2's S3 credentials for the packs' bucket: with all three, a large push uploads its pack. */\n readonly R2_ACCOUNT_ID?: string;\n readonly R2_ACCESS_KEY_ID?: string;\n readonly R2_SECRET_ACCESS_KEY?: string;\n"
|
|
@@ -149,7 +149,7 @@ var templates_default = {
|
|
|
149
149
|
"slot": "about",
|
|
150
150
|
"text": "Durable Object classes, an R2 bucket, and D1"
|
|
151
151
|
},
|
|
152
|
-
" for its people.\n// `ADMIN_TOKEN` and `SESSION_SECRET` are its secrets, set with `wrangler secret put`, or locally in\n// `.dev.vars`, which `ref0-git init` made. `APP_ORIGIN` is where it's served, the one origin sign-in\n// takes a POST from. `wrangler d1 create` adds `AUTH_DB`'s `database_id` on deploy, and\n// `migrations/sql/` holds its tables, which `wrangler d1 migrations apply
|
|
152
|
+
" for its people.\n// `ADMIN_TOKEN` and `SESSION_SECRET` are its secrets, set with `wrangler secret put`, or locally in\n// `.dev.vars`, which `ref0-git init` made. `APP_ORIGIN` is where it's served, the one origin sign-in\n// takes a POST from. `wrangler d1 create` adds `AUTH_DB`'s `database_id` on deploy, and\n// `migrations/sql/` holds its tables, which the app makes itself at its first sign-in, recorded as\n// `wrangler d1 migrations apply` records them.\n",
|
|
153
153
|
{
|
|
154
154
|
"slot": "signing",
|
|
155
155
|
"text": "// With R2's S3 credentials too, as the secrets `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID` and\n// `R2_SECRET_ACCESS_KEY`, a large push uploads its pack to the bucket in parts.\n"
|
|
@@ -327,7 +327,8 @@ var templates_default = {
|
|
|
327
327
|
"IMAGE_PROXY",
|
|
328
328
|
"R2_ACCOUNT_ID",
|
|
329
329
|
"R2_ACCESS_KEY_ID",
|
|
330
|
-
"R2_SECRET_ACCESS_KEY"
|
|
330
|
+
"R2_SECRET_ACCESS_KEY",
|
|
331
|
+
"CLIENT_IP_HEADER"
|
|
331
332
|
],
|
|
332
333
|
"signing": [
|
|
333
334
|
"R2_ACCOUNT_ID",
|
package/dist/init/versions.mjs
CHANGED
|
@@ -56,5 +56,5 @@ const initPacked = (name, at) => {
|
|
|
56
56
|
* the release, or the tarball `--from-checkout` names for that package. One it wrote moves to this
|
|
57
57
|
* run's spec; any other is the person's, a tarball of their own in `vendor/` too, and stays.
|
|
58
58
|
*/
|
|
59
|
-
const initWrote = (name, spec) => spec === "0.
|
|
59
|
+
const initWrote = (name, spec) => spec === "0.26.0" || spec !== void 0 && packedPath(name).test(spec);
|
|
60
60
|
export { catalog, contentNamed, frameworkPackages, initPacked, initWrote, nodeAppPackages, nodePackages, peerPackages, published, release, specOf, storePackages, unpacked, vercelPackages };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ref0-git",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "ref0-git, the CLI for a Git host built on @ref0/git, and git-remote-ref0, its remote helper",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@effect/platform-node-shared": "4.1.7",
|
|
27
|
-
"@ref0/git": "0.
|
|
28
|
-
"@ref0/infra": "0.
|
|
27
|
+
"@ref0/git": "0.26.0",
|
|
28
|
+
"@ref0/infra": "0.26.0",
|
|
29
29
|
"diff": "9.0.0",
|
|
30
30
|
"effect": "^4.1.7"
|
|
31
31
|
},
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"@effect/vitest": "4.1.7",
|
|
35
35
|
"@libsql/client": "0.18.0",
|
|
36
36
|
"@libsql/kysely-libsql": "0.4.1",
|
|
37
|
-
"@ref0/github": "0.
|
|
38
|
-
"@ref0/xdiff-wasm": "0.
|
|
37
|
+
"@ref0/github": "0.26.0",
|
|
38
|
+
"@ref0/xdiff-wasm": "0.26.0",
|
|
39
39
|
"@tanstack/react-start": "1.169.7",
|
|
40
40
|
"@types/node": "24.19.4",
|
|
41
41
|
"@types/pg": "8.23.1",
|