Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Better Auth 1.7.3+ identifies accounts by providerId/accountId and no longer writes issuer.
-- Refuse ambiguous existing identities before removing the old constraint or any data.
CREATE UNIQUE INDEX idx_account_provider_account ON account(providerId, accountId);
DROP INDEX idx_account_issuer_account;
ALTER TABLE account DROP COLUMN issuer;
2 changes: 1 addition & 1 deletion packages/skit-server-effect/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@effect/sql-d1": "4.1.1",
"@foldkit/ui": "0.170.0",
"@smolai/skit-core": "workspace:*",
"better-auth": "1.7.1",
"better-auth": "1.7.18",
"cn": "^0.3.0",
"effect": "4.1.1",
"fflate": "0.8.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export interface BootstrapClaimResult {
readonly username: string;
}

const CREDENTIAL_ISSUER = "local:credential";
const BootstrapClaim = Schema.Struct({ claimed: Schema.Number });
const UserCount = Schema.Struct({ count: Schema.Number });

Expand Down Expand Up @@ -125,8 +124,8 @@ export const makeBootstrap = (sql: DatabaseSqlClient, bootstrapSecret: string |
sql`INSERT INTO user (id, name, username, email, emailVerified, createdAt, updatedAt)
VALUES (${userId}, ${username}, ${username}, ${email}, 0, ${now}, ${now})`,
sql`INSERT INTO account
(id, issuer, accountId, providerId, userId, password, createdAt, updatedAt)
VALUES (${accountId}, ${CREDENTIAL_ISSUER}, ${userId}, 'credential', ${userId}, ${passwordHash}, ${now}, ${now})`,
(id, accountId, providerId, userId, password, createdAt, updatedAt)
VALUES (${accountId}, ${userId}, 'credential', ${userId}, ${passwordHash}, ${now}, ${now})`,
...provisionPrincipal(sql, { userId, username, principalId, timestamp }),
sql`INSERT INTO server_operators (principal_id, created_at)
VALUES (${principalId}, ${timestamp})`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export const expectedMigrations = [
"0008_device_authorization.sql",
"0009_feedback.sql",
"0010_owner_schema.sql",
"0011_better_auth_account_keys.sql",
] as const;
98 changes: 98 additions & 0 deletions packages/skit-server-effect/test/better-auth-migration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { applyD1Migrations, env, reset } from "cloudflare:test";
import { expect, it } from "@effect/vitest";
import { Effect } from "effect";
import { makeWebHandler } from "../src/http.js";
import { passwordCallbacks } from "../src/identity/internal/password.js";

const host = <A>(evaluate: () => Promise<A>) =>
// oxlint-disable-next-line skit/no-promise-wrappers -- D1, password callbacks and Worker handlers are Promise-only host APIs.
Effect.promise(evaluate);
const name = "0011_better_auth_account_keys";
const previous = () => env.TEST_MIGRATIONS.filter((entry) => entry.name < name);
const upgrade = () => env.TEST_MIGRATIONS.filter((entry) => entry.name.startsWith(name));

it.effect("preserves existing accounts and password sign-in when removing issuer", () =>
Effect.gen(function* () {
yield* host(() => reset());
yield* host(() => applyD1Migrations(env.DB, previous()));
const password = "existing account password";
const hash = yield* host(() => passwordCallbacks(globalThis.crypto).hash(password));
yield* host(() =>
env.DB.batch([
env.DB.prepare(`INSERT INTO user
(id, name, email, emailVerified, createdAt, updatedAt, username)
VALUES ('existing', 'Existing', 'existing@example.test', 1, 1, 1, 'existing')`),
env.DB.prepare(`INSERT INTO account
(id, issuer, accountId, providerId, userId, password, createdAt, updatedAt)
VALUES ('password-account', 'local:credential', 'existing', 'credential', 'existing', ?, 1, 1)`).bind(
hash,
),
env.DB.prepare(`INSERT INTO account
(id, issuer, accountId, providerId, userId, accessToken, refreshToken, createdAt, updatedAt)
VALUES ('github-account', 'https://github.com', 'existing', 'github', 'existing', 'access', 'refresh', 1, 1)`),
]),
);
const before = yield* host(() => env.DB.prepare("SELECT * FROM account ORDER BY id").all());
expect(upgrade()).toHaveLength(1);
yield* host(() => applyD1Migrations(env.DB, upgrade()));
expect(
(yield* host(() => env.DB.prepare("SELECT * FROM account ORDER BY id").all())).results,
).toEqual(before.results.map(({ issuer: _issuer, ...account }) => account));
const columns = yield* host(() =>
env.DB.prepare("PRAGMA table_info(account)").all<{ name: string }>(),
);
expect(columns.results.map(({ name }) => name)).not.toContain("issuer");
const web = makeWebHandler(env);
yield* Effect.gen(function* () {
const response = yield* host(() =>
web.handler(
new Request("https://registry.test/api/auth/sign-in/email", {
method: "POST",
headers: { "content-type": "application/json", origin: "https://registry.test" },
body: JSON.stringify({ email: "existing@example.test", password }),
}),
),
);
expect(response.status).toBe(200);
const cookie = (response.headers.get("set-cookie") ?? "").split(";", 1)[0]!;
const session = yield* host(() =>
web.handler(
new Request("https://registry.test/api/auth/get-session", {
headers: { cookie },
}),
),
);
expect(session.status).toBe(200);
expect(yield* host(() => session.json())).toMatchObject({ user: { id: "existing" } });
}).pipe(Effect.ensuring(host(() => web.dispose())));
}),
);

it.effect("refuses ambiguous provider account keys without changing existing accounts", () =>
Effect.gen(function* () {
yield* host(() => reset());
yield* host(() => applyD1Migrations(env.DB, previous()));
yield* host(() =>
env.DB.batch([
env.DB.prepare(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)
VALUES ('existing', 'Existing', 'existing@example.test', 1, 1, 1)`),
env.DB.prepare(`INSERT INTO account
(id, issuer, accountId, providerId, userId, createdAt, updatedAt)
VALUES ('first', 'first-issuer', 'shared', 'github', 'existing', 1, 1),
('second', 'second-issuer', 'shared', 'github', 'existing', 1, 1)`),
]),
);
const before = yield* host(() => env.DB.prepare("SELECT * FROM account ORDER BY id").all());
yield* host(() => expect(applyD1Migrations(env.DB, upgrade())).rejects.toThrow());
expect(
(yield* host(() => env.DB.prepare("SELECT * FROM account ORDER BY id").all())).results,
).toEqual(before.results);
expect(
yield* host(() =>
env.DB.prepare(
"SELECT name FROM sqlite_schema WHERE name = 'idx_account_issuer_account'",
).first(),
),
).toEqual({ name: "idx_account_issuer_account" });
}),
);
7 changes: 4 additions & 3 deletions packages/skit-server-effect/test/bootstrap-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const prepareIdentityDatabase = Effect.flatMap(D1Client.D1Client, (sql) =>
createdAt INTEGER NOT NULL, updatedAt INTEGER NOT NULL
)`),
sql.unsafe(`CREATE TABLE account (
id TEXT PRIMARY KEY, issuer TEXT NOT NULL, accountId TEXT NOT NULL,
id TEXT PRIMARY KEY, accountId TEXT NOT NULL,
providerId TEXT NOT NULL, userId TEXT NOT NULL, password TEXT,
createdAt INTEGER NOT NULL, updatedAt INTEGER NOT NULL
)`),
Expand Down Expand Up @@ -319,9 +319,10 @@ describe("bootstrap status", () => {
});
const account = yield* Effect.flatMap(
D1Client.D1Client,
(sql) => sql<{ issuer: string; password: string }>`SELECT issuer, password FROM account`,
(sql) =>
sql<{ providerId: string; password: string }>`SELECT providerId, password FROM account`,
);
expect(account[0]?.issuer).toBe("local:credential");
expect(account[0]?.providerId).toBe("credential");
expect(
yield* webPromise(() =>
passwordCallbacks(globalThis.crypto).verify({
Expand Down
92 changes: 35 additions & 57 deletions packages/skit-server-effect/test/release-download.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { env } from "cloudflare:test";
import { applyD1Migrations, env, reset } from "cloudflare:test";
import { D1Client } from "@effect/sql-d1";
import { describe, expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { afterEach, beforeEach } from "vitest";
import { makeWebHandler } from "../src/http.js";
import { BlobStore, blobStoreLayer, databaseLayer } from "../src/platform/cloudflare.js";

const platformLayer = Layer.merge(blobStoreLayer(env.SKIT_BLOBS), databaseLayer(env.DB));

const web = makeWebHandler(env);
let web: ReturnType<typeof makeWebHandler>;

const webPromise = <A>(evaluate: () => Promise<A>) =>
// oxlint-disable-next-line skit/no-promise-wrappers -- Fetch-compatible Worker handlers are Promise APIs; this test helper owns that host boundary.
Expand All @@ -30,45 +31,18 @@ const sha256 = (value: string) =>
),
);

const prepareDatabase = Effect.flatMap(D1Client.D1Client, (sql) =>
sql.batch([
sql.unsafe("DROP TABLE IF EXISTS releases"),
sql.unsafe("DROP TABLE IF EXISTS resource_grants"),
sql.unsafe("DROP TABLE IF EXISTS namespaces"),
sql.unsafe("DROP TABLE IF EXISTS team_memberships"),
sql.unsafe("DROP TABLE IF EXISTS personal_access_tokens"),
sql.unsafe("DROP TABLE IF EXISTS principals"),
sql.unsafe(`CREATE TABLE releases (
owner_slug TEXT NOT NULL,
skit_slug TEXT NOT NULL,
version TEXT NOT NULL,
release_id TEXT NOT NULL UNIQUE,
archive_object_key TEXT NOT NULL UNIQUE,
published_at TEXT NOT NULL,
visibility TEXT NOT NULL CHECK (visibility IN ('public', 'unlisted', 'private')),
PRIMARY KEY (owner_slug, skit_slug, version)
)`),
sql.unsafe(`CREATE TABLE principals (
principal_id TEXT PRIMARY KEY, better_auth_user_id TEXT UNIQUE,
state TEXT NOT NULL, authorization_generation INTEGER NOT NULL
)`),
sql.unsafe(`CREATE TABLE personal_access_tokens (
token_id TEXT PRIMARY KEY, principal_id TEXT NOT NULL, token_hash TEXT NOT NULL,
scopes_json TEXT NOT NULL, authorization_generation INTEGER NOT NULL,
expires_at TEXT, revoked_at TEXT, last_used_at TEXT
)`),
sql.unsafe(
"CREATE TABLE team_memberships (team_id TEXT, principal_id TEXT, PRIMARY KEY (team_id, principal_id))",
),
sql.unsafe(
"CREATE TABLE namespaces (namespace_slug TEXT PRIMARY KEY, subject_kind TEXT, subject_id TEXT)",
),
sql.unsafe(`CREATE TABLE resource_grants (
grant_id TEXT PRIMARY KEY, subject_kind TEXT, subject_id TEXT,
resource_kind TEXT, resource_id TEXT, permission TEXT
)`),
]),
);
beforeEach(async () => {
await reset();
await applyD1Migrations(env.DB, env.TEST_MIGRATIONS);
// Obsolete grants must never grant access, even if a database still contains them.
await env.DB.prepare(`CREATE TABLE resource_grants (
grant_id TEXT PRIMARY KEY, subject_kind TEXT, subject_id TEXT,
resource_kind TEXT, resource_id TEXT, permission TEXT
)`).run();
web = makeWebHandler(env);
});

afterEach(() => web.dispose());

const insertRelease = (input: {
version: string;
Expand All @@ -80,16 +54,15 @@ const insertRelease = (input: {
Effect.flatMap(D1Client.D1Client, (sql) =>
sql.unsafe(
`INSERT INTO releases
(owner_slug, skit_slug, version, release_id, archive_object_key, published_at, visibility)
VALUES ('tim', 'tools', ?, ?, ?, ?, ?)`,
(owner_slug, skit_slug, version, release_id, archive_object_key, published_at, visibility, archive_digest, archive_bytes)
VALUES ('tim', 'tools', ?, ?, ?, ?, ?, 'fixture-digest', 0)`,
[input.version, input.releaseId, input.objectKey, input.publishedAt, input.visibility],
),
);

describe("anonymous Release downloads", () => {
it.effect("returns 404 for an empty latest lookup without consulting credentials", () =>
Effect.gen(function* () {
yield* prepareDatabase;
yield* Effect.flatMap(D1Client.D1Client, (sql) => sql`DROP TABLE personal_access_tokens`);
const response = yield* request("/api/skits/tim/tools/releases/latest/download", {
headers: { authorization: "Bearer skit_pat_missing" },
Expand All @@ -101,7 +74,6 @@ describe("anonymous Release downloads", () => {

it.effect("serves an exact public Release as immutable", () =>
Effect.gen(function* () {
yield* prepareDatabase;
yield* insertRelease({
version: "1.0.0",
releaseId: "rel_public",
Expand All @@ -120,11 +92,15 @@ describe("anonymous Release downloads", () => {
const tokenHash = yield* sha256(token);
yield* Effect.flatMap(D1Client.D1Client, (sql) =>
sql.batch([
sql.unsafe("INSERT INTO principals VALUES ('principal_public', NULL, 'active', 1)"),
sql.unsafe(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)
VALUES ('user_public', 'Reader', 'public@example.test', 1, 1, 1)`),
sql.unsafe(`INSERT INTO principals
(principal_id, better_auth_user_id, state, authorization_generation, created_at, updated_at)
VALUES ('principal_public', 'user_public', 'active', 1, 'created', 'updated')`),
sql.unsafe(
`INSERT INTO personal_access_tokens
(token_id, principal_id, token_hash, scopes_json, authorization_generation)
VALUES ('pat_public', 'principal_public', ?, '[]', 1)`,
(token_id, principal_id, token_hash, scopes_json, authorization_generation, token_prefix, name, created_at)
VALUES ('pat_public', 'principal_public', ?, '[]', 1, 'skit_pat', 'fixture', 'created')`,
[tokenHash],
),
]),
Expand Down Expand Up @@ -171,7 +147,6 @@ describe("anonymous Release downloads", () => {

it.effect("selects the newest anonymously visible Release for latest", () =>
Effect.gen(function* () {
yield* prepareDatabase;
yield* insertRelease({
version: "1.0.0",
releaseId: "rel_public",
Expand Down Expand Up @@ -223,7 +198,6 @@ describe("anonymous Release downloads", () => {

it.effect("conceals private Releases and distinguishes missing archives", () =>
Effect.gen(function* () {
yield* prepareDatabase;
yield* insertRelease({
version: "1.0.0",
releaseId: "rel_private",
Expand Down Expand Up @@ -257,16 +231,19 @@ describe("anonymous Release downloads", () => {
"requires namespace ownership or current team membership for private Releases, never grants",
() =>
Effect.gen(function* () {
yield* prepareDatabase;
const token = "skit_pat_private_download";
const tokenHash = yield* sha256(token);
yield* Effect.flatMap(D1Client.D1Client, (sql) =>
sql.batch([
sql.unsafe("INSERT INTO principals VALUES ('principal_reader', NULL, 'active', 1)"),
sql.unsafe(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)
VALUES ('user_reader', 'Reader', 'reader@example.test', 1, 1, 1)`),
sql.unsafe(`INSERT INTO principals
(principal_id, better_auth_user_id, state, authorization_generation, created_at, updated_at)
VALUES ('principal_reader', 'user_reader', 'active', 1, 'created', 'updated')`),
sql.unsafe(
`INSERT INTO personal_access_tokens
(token_id, principal_id, token_hash, scopes_json, authorization_generation)
VALUES ('pat_reader', 'principal_reader', ?, '["authoring:write"]', 1)`,
(token_id, principal_id, token_hash, scopes_json, authorization_generation, token_prefix, name, created_at)
VALUES ('pat_reader', 'principal_reader', ?, '["authoring:write"]', 1, 'skit_pat', 'fixture', 'created')`,
[tokenHash],
),
sql.unsafe(
Expand Down Expand Up @@ -311,7 +288,7 @@ describe("anonymous Release downloads", () => {
expect((yield* request("/api/skits/tim/tools/releases/1.0.0/download")).status).toBe(404);
for (const version of ["1.0.0", "latest"])
expect((yield* download(version)).status).toBe(404);
yield* sql`INSERT INTO namespaces VALUES ('tim', 'principal', 'principal_reader')`;
yield* sql`INSERT INTO namespaces VALUES ('tim', 'principal', 'principal_reader', 'created')`;
for (const [version, selected, content] of [
["1.0.0", "1.0.0", "private archive"],
["latest", "2.0.0", "newer private archive"],
Expand All @@ -324,11 +301,12 @@ describe("anonymous Release downloads", () => {
}
yield* sql.batch([
sql`UPDATE namespaces SET subject_kind = 'team', subject_id = 'team_owner' WHERE namespace_slug = 'tim'`,
sql`INSERT INTO team_memberships VALUES ('team_other', 'principal_reader')`,
sql`INSERT INTO teams VALUES ('team_other', 'other', 'Other', 'created'), ('team_owner', 'owner', 'Owner', 'created')`,
sql`INSERT INTO team_memberships VALUES ('team_other', 'principal_reader', 'member', 'created')`,
]);
for (const version of ["1.0.0", "latest"])
expect((yield* download(version)).status).toBe(404);
yield* sql`INSERT INTO team_memberships VALUES ('team_owner', 'principal_reader')`;
yield* sql`INSERT INTO team_memberships VALUES ('team_owner', 'principal_reader', 'member', 'created')`;
for (const version of ["1.0.0", "latest"])
expect((yield* download(version)).status).toBe(200);
yield* sql`DROP TABLE resource_grants`;
Expand Down
12 changes: 0 additions & 12 deletions patches/better-auth@1.7.1.patch

This file was deleted.

Loading
Loading