Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(resources): credit each resource and keep its license beside it
Elian Doran0d5adf04ae99
diff --git a/apps/client/src/translations/en-GB/translation.json b/apps/client/src/translations/en-GB/translation.jsonindex 70227cdc94..7a6a9ea909 100644--- a/apps/client/src/translations/en-GB/translation.json+++ b/apps/client/src/translations/en-GB/translation.json@@ -246,5 +246,8 @@},"relation_map": {"note_color": "Note colour"+ },+ "resource_download": {+ "license": "{{license}} licence"}}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 881de63f85..c142259867 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4613,7 +4613,6 @@"title": "Download required","intro": "Trilium needs to download the following files before it can continue. They are saved on this device and are not synced, so each of your devices downloads them separately.","partially_downloaded": "Already downloaded",- "sources": "From {{sources}}","total": "Download size","free_space": "Free space on disk: {{size}}","not_enough_space": "The download needs {{size}}, but only {{free}} is free on this device. Free up some space, then close this and try again.",@@ -4626,7 +4625,8 @@"failed_title": "Download failed","license": "{{license}} license","verify": "Verify",- "unverified": "{{size}} already on this device, checked instead of downloaded"+ "unverified": "{{size}} already on this device, checked instead of downloaded",+ "credits": "By <Author>{{author}}</Author>, from {{sources}}"},"transcription_options": {"recognition_title": "Speech recognition",diff --git a/apps/client/src/widgets/dialogs/resource_download.spec.tsx b/apps/client/src/widgets/dialogs/resource_download.spec.tsxindex 93cc5c0ade..52fbba0bb8 100644--- a/apps/client/src/widgets/dialogs/resource_download.spec.tsx+++ b/apps/client/src/widgets/dialogs/resource_download.spec.tsx@@ -16,6 +16,15 @@ const mocks = vi.hoisted(() => ({vi.mock("../../services/i18n", () => ({t: (key: string, values?: object) => (values ? `${key}:${JSON.stringify(values)}` : key)}));+// The real i18n is not initialized under test, so `Trans` would render the bare key and drop what+// it wires in; the stub renders its values and the components themselves.+vi.mock("react-i18next", () => ({+ Trans: ({ i18nKey, values, components }: {+ i18nKey: string, values: object, components: Record<string, preact.VNode>+ }) => (+ <span data-i18n-key={i18nKey}>{JSON.stringify(values)}{Object.values(components)}</span>+ )+}));vi.mock("../../services/server", () => ({default: { get: mocks.get, post: mocks.post }}));@@ -38,6 +47,9 @@ const STATUS: ResourcesStatusResponse = {downloadedSize: 200,unverifiedSize: 0,sources: [ "huggingface.co", "github.com" ],+ author: "NVIDIA",+ homepage: "https://example.com/model",+ licenseUrl: "https://creativecommons.org/licenses/by/4.0/",installed: false,directory: null} ],@@ -70,9 +82,14 @@ describe("ResourceDownloadDialog", () => {const row = container.querySelector(".resource-download-item");expect(row?.querySelector(".resource-download-icon")?.classList).toContain("bx-captions");expect(row?.textContent).toContain("Speech recognition model");- expect(text(".resource-download-meta")).toContain("huggingface.co, github.com");- expect(text(".resource-download-license"))- .toBe(`resource_download.license:{"license":"CC-BY-4.0"}`);+ const credits = container.querySelector(".resource-download-meta");+ expect(credits?.querySelector("[data-i18n-key]")?.textContent)+ .toBe(`{"author":"NVIDIA","sources":"huggingface.co, github.com"}`);+ expect(credits?.querySelector(".resource-download-author")?.getAttribute("href"))+ .toBe("https://example.com/model");+ const license = credits?.querySelector(".resource-download-license");+ expect(license?.textContent).toBe(`resource_download.license:{"license":"CC-BY-4.0"}`);+ expect(license?.getAttribute("href")).toBe("https://creativecommons.org/licenses/by/4.0/");expect(row?.querySelector("[role=progressbar]")?.getAttribute("aria-valuenow")).toBe("200");expect(row?.querySelector(".resource-download-progress")?.textContent).toContain(`"received":"200 B","total":"700 B"`);diff --git a/apps/client/src/widgets/dialogs/resource_download.tsx b/apps/client/src/widgets/dialogs/resource_download.tsxindex f7c6d5c08d..7b9e95ac9f 100644--- a/apps/client/src/widgets/dialogs/resource_download.tsx+++ b/apps/client/src/widgets/dialogs/resource_download.tsx@@ -4,7 +4,9 @@ import type {ResourceDownloadProgress, ResourceDownloadState, ResourceInfo, ResourcesStatusResponse,WebSocketMessage} from "@triliumnext/commons";+import type { ComponentChildren } from "preact";import { useEffect, useRef, useState } from "preact/hooks";+import { Trans } from "react-i18next";import { t } from "../../services/i18n";import server from "../../services/server";@@ -225,17 +227,12 @@ function ResourceItem({ resource, unitOf, state, file }: ResourceItemProps) {<div className="tn-card-option-label"><span className="tn-card-option-title">{resource.title}</span><small className="tn-card-option-description">{resource.description}</small>- <small className="tn-card-option-description resource-download-meta">- {t("resource_download.sources", { sources: resource.sources.join(", ") })}- {" · "}- <span className="resource-download-license">- {t("resource_download.license", { license: resource.license })}- </span>+ <ResourceCredits resource={resource}>{resource.unverifiedSize > 0 && <>{" · "}{t("resource_download.unverified", { size: formatSize(resource.unverifiedSize) })}</>}- </small>+ </ResourceCredits>{isActive && state && (<RowProgressreceived={state.receivedBytes}@@ -258,6 +255,46 @@ function ResourceItem({ resource, unitOf, state, file }: ResourceItemProps) {);}+/**+ * Who made a resource and where its files come from, then its license, as the license asks a+ * resource to be credited: the author links to the original work and the license to its text.+ */+export function ResourceCredits({ resource, children }: {+ resource: ResourceInfo;+ children?: ComponentChildren;+}) {+ return (+ <small className="tn-card-option-description resource-download-meta">+ <Trans+ i18nKey="resource_download.credits"+ values={{ author: resource.author, sources: resource.sources.join(", ") }}+ components={{+ Author: <ExternalLink className="resource-download-author" href={resource.homepage} />+ }}+ />+ {" · "}+ <ExternalLink className="resource-download-license" href={resource.licenseUrl}>+ {t("resource_download.license", { license: resource.license })}+ </ExternalLink>+ {children}+ </small>+ );+}++interface ExternalLinkProps {+ className: string;+ href: string;+ children?: ComponentChildren;+}++function ExternalLink({ className, href, children }: ExternalLinkProps) {+ return (+ <a className={`tn-link external ${className}`} href={href} target="_blank" rel="noopener noreferrer">+ {children}+ </a>+ );+}+interface RowProgressProps {received: number;total: number;diff --git a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx b/apps/client/src/widgets/type_widgets/options/resources.spec.tsxindex 6094279cb5..e3231a1d8f 100644--- a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/resources.spec.tsx@@ -16,6 +16,16 @@ const mocks = vi.hoisted(() => ({handlers: [] as ((message: WebSocketMessage) => void)[]}));+// The real i18n is not initialized under test, so `Trans` would render the bare key and drop what+// it wires in; the stub renders its values and the components themselves.+vi.mock("react-i18next", () => ({+ Trans: ({ i18nKey, values, components }: {+ i18nKey: string, values: object, components: Record<string, preact.VNode>+ }) => (+ <span data-i18n-key={i18nKey}>{JSON.stringify(values)}{Object.values(components)}</span>+ )+}));+vi.mock("../../../services/server", () => ({default: {get: async (url: string) => {@@ -121,6 +131,10 @@ describe("ResourcesSettings", () => {]);expect([ ...host.querySelectorAll(".resources-size") ].map((size) => size.textContent)).toEqual([ "2.00 GiB", "0.01 GiB", "2.00 GiB" ]);+ expect(rows[0].querySelector(".resource-download-author")?.getAttribute("href"))+ .toBe("https://example.com/model");+ expect(rows[0].querySelector(".resource-download-license")?.getAttribute("href"))+ .toBe("https://opensource.org/license/mit");});it("lists files copied in but not yet checked, and counts them in the space used", async () => {@@ -271,6 +285,9 @@ function resource(overrides: Partial<ResourceInfo> & { id: string }): ResourceIndownloadedSize: 0,unverifiedSize: 0,sources: [ "example.com" ],+ author: "Test Lab",+ homepage: "https://example.com/model",+ licenseUrl: "https://opensource.org/license/mit",installed: false,directory: null,...overridesdiff --git a/apps/client/src/widgets/type_widgets/options/resources.tsx b/apps/client/src/widgets/type_widgets/options/resources.tsxindex 1f4da2f54a..118f8fff2a 100644--- a/apps/client/src/widgets/type_widgets/options/resources.tsx+++ b/apps/client/src/widgets/type_widgets/options/resources.tsx@@ -13,6 +13,7 @@ import openService from "../../../services/open";import server from "../../../services/server";import { formatSize, isElectron } from "../../../services/utils";import { subscribeToMessages, unsubscribeToMessage } from "../../../services/ws";+import { ResourceCredits } from "../../dialogs/resource_download";import ActionButton from "../../react/ActionButton";import { Card, CardSection } from "../../react/Card";import Icon from "../../react/Icon";@@ -141,11 +142,7 @@ function ResourceRow({ resource, unitOf, onDeleted }: ResourceRowProps) {onDelete={() => void remove()}><small className="tn-card-option-description">{resource.description}</small>- <small className="tn-card-option-description">- {t("resource_download.sources", { sources: resource.sources.join(", ") })}- {" · "}- {t("resource_download.license", { license: resource.license })}- </small>+ <ResourceCredits resource={resource} /></EntryRow>);}diff --git a/apps/desktop/src/services/transcription/model.ts b/apps/desktop/src/services/transcription/model.tsindex fe44583d64..abcb68a3f7 100644--- a/apps/desktop/src/services/transcription/model.ts+++ b/apps/desktop/src/services/transcription/model.ts@@ -80,9 +80,13 @@ const PARAKEET_FP32_FILES: ResourceFile[] = [/** Parakeet TDT 0.6B v3 at each precision: the files `loadSherpaEngine()` reads as its recognizer. */export const RECOGNIZER_MODELS: ResourceDefinition[] = [parakeet(MODEL_CHOICES["parakeet-int8"].resourceId, PARAKEET_INT8_FILES,- () => t("transcription.recognizer-int8-title")),+ () => t("transcription.recognizer-int8-title"),+ "Exported to ONNX and quantized to int8 by the k2-fsa sherpa-onnx project, "+ + "https://huggingface.co/csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8."),parakeet(MODEL_CHOICES["parakeet-fp32"].resourceId, PARAKEET_FP32_FILES,- () => t("transcription.recognizer-fp32-title"))+ () => t("transcription.recognizer-fp32-title"),+ "Exported to ONNX by the k2-fsa sherpa-onnx project, "+ + "https://huggingface.co/csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3.")];export const VAD_MODEL: ResourceDefinition = {@@ -91,6 +95,13 @@ export const VAD_MODEL: ResourceDefinition = {description: () => t("transcription.vad-description"),icon: "bx bx-pulse",license: "MIT",+ attribution: {+ work: "Silero VAD",+ author: "Silero Team",+ homepage: "https://github.com/snakers4/silero-vad",+ copyright: "Copyright (c) 2020-present Silero Team",+ changes: "Redistributed in the releases of the k2-fsa sherpa-onnx project."+ },files: [ {path: VAD_FILE,url: `${SHERPA_RELEASES}/asr-models/${VAD_FILE}`,@@ -104,7 +115,14 @@ export const SPEAKER_MODEL: ResourceDefinition = {title: () => t("transcription.speaker-title"),description: () => t("transcription.speaker-description"),icon: "bx bx-user-voice",+ // NGC states TitaNet is under the license of the NeMo toolkit, which is Apache-2.0.license: "Apache-2.0",+ attribution: {+ work: "TitaNet-S",+ author: "NVIDIA",+ homepage: "https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/titanet_small",+ changes: "Exported to ONNX by the k2-fsa sherpa-onnx project."+ },files: [ {path: SPEAKER_FILE,url: `${SHERPA_RELEASES}/speaker-recongition-models/${SPEAKER_FILE}`,@@ -136,13 +154,20 @@ export function getModelPaths(modelId: string | null, identifySpeakers: boolean)};}-function parakeet(id: string, files: ResourceFile[], title: () => string): ResourceDefinition {+function parakeet(id: string, files: ResourceFile[], title: () => string,+ changes: string): ResourceDefinition {return {id,title,description: () => t("transcription.recognizer-description"),icon: "bx bx-captions",license: "CC-BY-4.0",+ attribution: {+ work: "Parakeet TDT 0.6B v3",+ author: "NVIDIA",+ homepage: "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3",+ changes+ },files};}diff --git a/apps/server/src/assets/licenses/Apache-2.0.txt b/apps/server/src/assets/licenses/Apache-2.0.txtnew file mode 100644index 0000000000..d645695673--- /dev/null+++ b/apps/server/src/assets/licenses/Apache-2.0.txt@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/apps/server/src/services/resources.spec.ts b/apps/server/src/services/resources.spec.tsindex 761a7afc8e..a969f905bb 100644--- a/apps/server/src/services/resources.spec.ts+++ b/apps/server/src/services/resources.spec.ts@@ -123,6 +123,9 @@ describe("ResourceManager", () => {downloadedSize: MODEL.length + TOKENS.length,unverifiedSize: 0,sources: [ "127.0.0.1" ],+ author: "Test Lab",+ homepage: "https://example.com/test-model",+ licenseUrl: "https://opensource.org/license/mit",installed: true,directory} ]);@@ -175,6 +178,25 @@ describe("ResourceManager", () => {expect((await impatient.getStatus([ "test.model" ])).resources[0].downloadedSize).toBe(STALL_AFTER);});+ it("writes a notice with the attribution and license beside the files it installs", async () => {+ manager.register(defineModel(), {+ ...defineModel({ id: "test.apache" }),+ license: "Apache-2.0",+ attribution: { work: "Apache model", author: "Foundation", homepage: "https://example.com/apache" }+ });+ manager.startDownload([ "test.model", "test.apache" ]);+ expect((await waitForEnd()).status).toBe("succeeded");++ const mit = fs.readFileSync(path.join(resourceDirectory(), "NOTICE.txt"), "utf8");+ for (const expected of [ "Test model", "Test Lab", "https://example.com/test-model",+ "Converted to ONNX.", "Copyright (c) 2024 Test Lab", "Permission is hereby granted" ]) {+ expect(mit).toContain(expected);+ }+ const apache = fs.readFileSync(path.join(manager.getPath("test.apache") ?? "", "NOTICE.txt"), "utf8");+ expect(apache).toContain("https://www.apache.org/licenses/LICENSE-2.0");+ expect(apache).toContain("TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION");+ });+it("downloads through the fetch it is given, such as one that follows the system proxy", async () => {const proxied = vi.fn((url: string, init: RequestInit) => fetch(url, init));manager.setFetch(proxied);@@ -398,6 +420,8 @@ describe("ResourceManager", () => {manager.register(defineModel());expect(() => manager.register(defineModel())).toThrow(/already registered/);expect(() => manager.register(defineModel({ id: "Test Model" }))).toThrow(/invalid ID/);+ expect(() => manager.register({ ...defineModel({ id: "test.unlicensed" }), license: "WTFPL" }))+ .toThrow(/license/);expect(() => manager.register({ ...defineModel({ id: "test.escape" }), files: [ file("../outside", MODEL) ] })).toThrow(/outside its directory/);expect(() => manager.getPath("test.unknown")).toThrow();@@ -413,6 +437,13 @@ function defineModel({ id = "test.model", modelUrl = "/model.bin", tokensUrl = "description: () => "For tests",icon: "bx bx-test-tube",license: "MIT",+ attribution: {+ work: "Test model",+ author: "Test Lab",+ homepage: "https://example.com/test-model",+ copyright: "Copyright (c) 2024 Test Lab",+ changes: "Converted to ONNX."+ },files: [{ ...file("nested/model.bin", MODEL), url: `${baseUrl}${modelUrl}` },{ path: "tokens.txt", url: `${baseUrl}${tokensUrl}`, size: tokensSize, sha256: tokensHash }diff --git a/apps/server/src/services/resources.ts b/apps/server/src/services/resources.tsindex 2c1f57b0ca..64c40c0846 100644--- a/apps/server/src/services/resources.ts+++ b/apps/server/src/services/resources.ts@@ -11,6 +11,7 @@ import { pipeline } from "node:stream/promises";import type { ReadableStream as NodeReadableStream } from "node:stream/web";import dataDirs from "./data_dir.js";+import { RESOURCE_DIR } from "./resource_dir.js";/** One file of a resource, downloaded from `url` and accepted only if it matches `size` and `sha256`. */export interface ResourceFile {@@ -29,11 +30,26 @@ export interface ResourceDefinition {description(): string;/** Boxicons classes, `bx bx-…`, for the download dialog. */icon: string;- /** The SPDX identifier of the license the files are under, such as `CC-BY-4.0`. */+ /** The SPDX identifier of the license the files are under, one of {@link LICENSES}. */license: string;+ attribution: ResourceAttribution;files: ResourceFile[];}+/** Who made a resource, as its license asks it to be credited. */+export interface ResourceAttribution {+ /** The name of the original work, such as `Parakeet TDT 0.6B v3`. */+ work: string;+ /** Who made the original, such as `NVIDIA`. */+ author: string;+ /** Where the original is published. */+ homepage: string;+ /** The copyright line the work states, which its license asks to keep. */+ copyright?: string;+ /** How the files downloaded differ from the original, in English, for the notice. */+ changes?: string;+}+/** The part of `fetch()` a download uses. */export type ResourceFetch = (url: string, init: RequestInit) => Promise<Response>;@@ -51,6 +67,44 @@ interface Download {/** The size and modification time of each verified file of a resource, by its path. */type VerifiedFiles = Record<string, { size: number; mtimeMs: number }>;+/** The licenses a resource can be under: where each is published, and the text its notice carries. */+const LICENSES: Record<string, { url: string; getText(): string }> = {+ "CC-BY-4.0": {+ url: "https://creativecommons.org/licenses/by/4.0/",+ getText: () => [+ "Licensed under the Creative Commons Attribution 4.0 International License,",+ "https://creativecommons.org/licenses/by/4.0/legalcode. The licensor offers the",+ "material as is and makes no representations or warranties of any kind concerning",+ "it; see Section 5 of the license, Disclaimer of Warranties and Limitation of Liability."+ ].join("\n")+ },+ "MIT": {+ url: "https://opensource.org/license/mit",+ getText: () => [+ "Permission is hereby granted, free of charge, to any person obtaining a copy",+ "of this software and associated documentation files (the \"Software\"), to deal",+ "in the Software without restriction, including without limitation the rights",+ "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",+ "copies of the Software, and to permit persons to whom the Software is",+ "furnished to do so, subject to the following conditions:",+ "",+ "The above copyright notice and this permission notice shall be included in all",+ "copies or substantial portions of the Software.",+ "",+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",+ "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",+ "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",+ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",+ "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",+ "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",+ "SOFTWARE."+ ].join("\n")+ },+ "Apache-2.0": {+ url: "https://www.apache.org/licenses/LICENSE-2.0",+ getText: () => fs.readFileSync(path.join(RESOURCE_DIR, "licenses", "Apache-2.0.txt"), "utf8")+ }+};const ID_PATTERN = /^[a-z0-9-]+(\.[a-z0-9-]+)*$/;const CONTENT_HASH_PATTERN = /^[0-9a-f]{12}$/;const PROGRESS_INTERVAL_MS = 250;@@ -58,6 +112,8 @@ const PROGRESS_INTERVAL_MS = 250;const STALL_TIMEOUT_MS = 30_000;/** How many hex digits of the files' combined hash a resource's directory name carries. */const CONTENT_HASH_LENGTH = 12;+/** Credits a resource and states its license, in its directory, so that a copy of it carries both. */+const NOTICE_FILE = "NOTICE.txt";/** Holds the {@link VerifiedFiles} of a resource, in its directory. */const VERIFIED_FILE = ".verified.json";@@ -215,6 +271,7 @@ export class ResourceManager {verified[file.path] = { size, mtimeMs };await writeVerifiedFiles(directory, verified);}+ await writeNotice(directory, definition);state.done = true;report(true);getLog().info(`Resources: installed ${definition.id} in ${directory}.`);@@ -324,6 +381,9 @@ export class ResourceManager {downloadedSize,unverifiedSize,sources: [ ...new Set(definition.files.map(({ url }) => new URL(url).hostname)) ],+ author: definition.attribution.author,+ homepage: definition.attribution.homepage,+ licenseUrl: LICENSES[definition.license].url,installed: installedDirectory !== null,directory: installedDirectory};@@ -432,10 +492,13 @@ export async function downloadFile(file: ResourceFile, destination: string, sign}}-function validateDefinition({ id, files }: ResourceDefinition) {+function validateDefinition({ id, license, files }: ResourceDefinition) {if (!ID_PATTERN.test(id)) {throw new Error(`The resource ${id} has an invalid ID.`);}+ if (!Object.hasOwn(LICENSES, license)) {+ throw new Error(`The resource ${id} has a license with no notice: ${license}.`);+ }for (const file of files) {const segments = file.path.split("/");if (segments.some((segment) => !segment || segment === "." || segment === "..")) {@@ -558,3 +621,26 @@ function sumSizes(files: ResourceFile[]) {export default new ResourceManager(dataDirs.RESOURCES_DIR, (download) => {ws.sendMessageToAllClients({ type: "resource-download", download });});++/**+ * Writes `NOTICE.txt` into the directory of a resource: the original work and who made it, how the+ * files differ from it, where they came from, and the license with the text it asks copies to carry.+ */+async function writeNotice(directory: string, { license, attribution, files }: ResourceDefinition) {+ const { work, author, homepage, copyright, changes } = attribution;+ const { url, getText } = LICENSES[license];+ const lines = [+ `${work} by ${author}`,+ homepage,+ "",+ ...(changes ? [ `Changes: ${changes}`, "" ] : []),+ "Downloaded by Trilium from:",+ ...files.map((file) => ` ${file.url}`),+ "",+ `License: ${license}, ${url}`,+ ...(copyright ? [ copyright ] : []),+ "",+ getText()+ ];+ await fs.promises.writeFile(path.join(directory, NOTICE_FILE), lines.join("\n"));+}diff --git a/packages/commons/src/lib/resources.ts b/packages/commons/src/lib/resources.tsindex 89b0f69f66..67e31a88bc 100644--- a/packages/commons/src/lib/resources.ts+++ b/packages/commons/src/lib/resources.ts@@ -25,6 +25,12 @@ export interface ResourceInfo {unverifiedSize: number;/** The host names its files are downloaded from. */sources: string[];+ /** Who made the original work. */+ author: string;+ /** Where the original work is published. */+ homepage: string;+ /** Where its license is published. */+ licenseUrl: string;installed: boolean;/** The directory holding its files while it is installed, else `null`. */directory: string | null;