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
32 changes: 32 additions & 0 deletions convex/evidenceLibraries/paperLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { afterEach, expect, it, vi } from "vitest";
import { internal } from "../_generated/api";
import { createReadySetupFixture } from "../../tests/helpers/evidence-library-setup-fixture";
import { fakeStore, storeAnswer, storedAddress, stubPaperStore } from "../lib/paperPdfs.test-support";

afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });

Expand Down Expand Up @@ -92,3 +93,34 @@ it("finds papers by a title on the index the site searches, for a community's si
// Too short to be a title.
expect((await ask("ab")).status).toBe(400);
});

it("gives a community a link to Openscholar's stored copy of a paper's PDF, for nothing, and no one else", async () => {
const { t, created, clerkUserId } = await createReadySetupFixture("paper_links_stored");
const libraryId = created.libraryId;
const token = "els_" + "e".repeat(43);
await t.run(async (ctx) => {
// The community's machine credential, as its setup stored one: its digest is this token's.
const credential = await ctx.db.query("evidenceLibraryCredentials").withIndex("by_libraryId_and_credentialKey", (q) => q.eq("libraryId", libraryId).eq("credentialKey", "library-service")).unique();
const digest = createHash("sha256").update(token).digest("hex");
if (credential) await ctx.db.patch("evidenceLibraryCredentials", credential._id, { credentialDigest: digest });
else await ctx.db.insert("evidenceLibraryCredentials", { libraryId, credentialKey: "library-service", encryptedValue: "unused", credentialDigest: digest, validationState: "valid", createdByClerkUserId: clerkUserId, updatedByClerkUserId: clerkUserId, createdAt: 1, updatedAt: 1 });
});
stubPaperStore();
fakeStore.reset();
fakeStore.objects.set("openalex/W7.pdf", new TextEncoder().encode("%PDF-1.7"));
vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => (await storeAnswer(input, init)) ?? new Response("Not found", { status: 404 }));
const ask = (paper: Record<string, string>, credential = token) =>
t.fetch("/api/v1/evidence-libraries/papers/stored-pdf", { method: "POST", headers: { Authorization: `Bearer ${credential}`, "Content-Type": "application/json" }, body: JSON.stringify({ contractVersion: 1, libraryId, ...paper }) });

// A copy the store holds comes back as a signed link to it.
const held = await ask({ openalexId: "https://openalex.org/W7", url: "https://example.org/w7.pdf" });
expect(held.status).toBe(200);
expect(((await held.json()) as { link: string }).link).toContain(`${storedAddress("openalex/W7.pdf")}?`);
// A paper it has no copy of names none, and nothing is bought or fetched for it.
expect(await (await ask({ openalexId: "W8" })).json()).toEqual({ link: null });
// Nobody's charged for a community's read.
expect(await t.run(async (ctx) => (await ctx.db.query("paperPdfReads").take(1)).length)).toBe(0);

expect((await ask({ openalexId: "W7" }, "els_" + "f".repeat(43))).status).toBe(401);
expect((await ask({})).status).toBe(400);
});
27 changes: 27 additions & 0 deletions convex/evidenceLibraries/paperLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { requireAppUrl } from "../lib/env";
import { jsonResponse, readBearerCredential } from "../lib/libraryServiceHttp";
import { readConvexErrorData } from "../lib/errors";
import { digestOpaqueToken } from "../lib/opaqueTokenDigest";
import { storedCopyLink } from "../lib/paperPdfs";
import { PAGE_ORDERED_SORT, readSearchPage, readWork } from "../paperSets/openalex";
import { spender } from "../paperSets/search";
import { OpenAlexLimitedError } from "../../lib/openalex/limited";
Expand All @@ -15,6 +16,7 @@ import { paperLinkOf } from "../../lib/papers/paper-links";
import { ADDED_PAPERS_MAX } from "../../lib/evidence-libraries/added-papers";
import { publicLibraryHeaders } from "../../lib/evidence-libraries/library-shield";
import { REPORTS_ASKED_MAX, REPORTS_PER_READ } from "../../lib/reports/report";
import { MAX_PDF_URL_LENGTH } from "../../lib/pdf/url-allowlist";

/** A paper as a community takes it: its OpenAlex work, its DOI, or both. */
export type PaperIds = { openalexId: string | null; doi: string | null };
Expand Down Expand Up @@ -108,6 +110,31 @@ export const resolvePapers: ReturnType<typeof httpAction> = httpAction(async (ct
return answerPapers(libraryId, async () => await Promise.all(links.map((link) => paperOfLink(ctx, link, spend, { withDoi: true }))));
});

const storedPdfSchema = z
.object({
contractVersion: z.literal(1),
libraryId: z.string().min(1).max(128),
openalexId: z.string().min(1).max(64).optional(),
url: z.string().min(1).max(MAX_PDF_URL_LENGTH).optional(),
})
.strict();

/**
* `POST /api/v1/evidence-libraries/papers/stored-pdf`, for a community's import: a link to Openscholar's stored copy
* of a paper's PDF, good for an hour, by the paper's OpenAlex work or by the address a copy was fetched from. `link`
* is null when the store has none. A community reads a stored copy for nothing and never buys one: only a read inside
* Openscholar is charged. With the community's machine credential.
*/
export const storedPdf: ReturnType<typeof httpAction> = httpAction(async (ctx, request) => {
const credential = readBearerCredential(request);
if (!credential) return jsonResponse(401, { error: { code: "invalid_service_credential", retryable: false } });
const parsed = storedPdfSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success || (!parsed.data.openalexId && !parsed.data.url)) return jsonResponse(400, { error: { code: "invalid_request", retryable: false } });
const { libraryId, openalexId, url } = parsed.data;
if (!(await isCommunity(ctx, libraryId, credential))) return jsonResponse(401, { error: { code: "invalid_service_credential", retryable: false } });
return jsonResponse(200, { link: await storedCopyLink({ ...(openalexId ? { openalexId } : {}), ...(url ? { url } : {}) }) });
});

const reportsSchema = z
.object({
contractVersion: z.literal(1),
Expand Down
4 changes: 3 additions & 1 deletion convex/http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { paperSubmissionStatus } from "./evidenceLibraries/submissionsHttp";
import { reportRecords, resolvePapers, searchPapersByTitle } from "./evidenceLibraries/paperLinks";
import { reportRecords, resolvePapers, searchPapersByTitle, storedPdf } from "./evidenceLibraries/paperLinks";
import { zenodoToken } from "./evidenceLibraries/zenodoToken";
import { reports as searchIndexReports } from "./reports/searchIndex";
import { catalog as topicCatalog, detail as topicDetail, associations as topicAssociations, associationBatch as topicAssociationBatch } from "./topics/serviceHttp";
Expand Down Expand Up @@ -52,6 +52,8 @@ http.route({path: "/api/v1/evidence-libraries/author-associations", method: "POS
http.route({path: "/api/v1/evidence-libraries/paper-submissions", method: "POST", handler: paperSubmissionStatus});
http.route({path: "/api/v1/evidence-libraries/papers/resolve", method: "POST", handler: resolvePapers});
http.route({path: "/api/v1/evidence-libraries/reports/records", method: "POST", handler: reportRecords});
// A community's import reads Openscholar's stored copy of a paper's PDF, for nothing.
http.route({path: "/api/v1/evidence-libraries/papers/stored-pdf", method: "POST", handler: storedPdf});
// A community archiving in its owner's own Zenodo account asks for the account's current token (#1237).
http.route({path: "/api/v1/evidence-libraries/zenodo-token", method: "POST", handler: zenodoToken});
// A community's reader looks for a paper to suggest by its title, on the index the site searches.
Expand Down
11 changes: 11 additions & 0 deletions convex/lib/paperPdfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,17 @@ async function keep(key: string, bytes: Uint8Array) {
}
}

/**
* A link to the stored copy of a paper, for an hour, or null when the store has none. Nothing is charged: this is for
* a community's import, which reads a stored copy for nothing. A read inside Openscholar goes through `paperPdf`.
*/
export async function storedCopyLink(paper: Pick<PaperRef, "openalexId" | "url">): Promise<string | null> {
for (const key of await paperKeys(paper)) {
if ((await storedSize(key)) !== null) return storedLink(key);
}
return null;
}

const NOT_KEPT = "This paper's PDF couldn't be kept to send. Try again in a moment.";

/** A link a model's provider can fetch the stored copy from, for an hour. */
Expand Down
Loading