Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): decode share URL v2 in core, docs splash, and desktop (PRD-8043) (#3565)

serafin-garciab8bfb906c989
diff --git a/.changeset/share-content-directory-links.md b/.changeset/share-content-directory-links.md
new file mode 100644
index 000000000..1cf79db63
--- /dev/null
+++ b/.changeset/share-content-directory-links.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Prepares share links to work correctly for projects whose Open Knowledge content lives in a subdirectory of the repository (configured with `content.dir`). Existing share links are unaffected.
diff --git a/.github/scripts/probe-share-contract.mjs b/.github/scripts/probe-share-contract.mjs
new file mode 100644
index 000000000..f680b7fa2
--- /dev/null
+++ b/.github/scripts/probe-share-contract.mjs
@@ -0,0 +1,386 @@
+#!/usr/bin/env node
+
+import { createHash } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+export const FIXED_PROBE_CASE_IDS = ['v2-one-segment-document', 'v2-one-segment-content-root'];
+
+const REQUIRED_EPOCH = 2;
+const MANIFEST_PATH = '/.well-known/openknowledge-share-contract.json';
+const SHA256_PATTERN = /^[0-9a-f]{64}$/;
+const DEPLOYMENT_SHA_PATTERN = /^[0-9a-f]{40}$/;
+const REQUEST_TIMEOUT_MS = 15_000;
+
+class ShareContractProbeError extends Error {
+ constructor(code, message, evidence) {
+ super(message);
+ this.name = 'ShareContractProbeError';
+ this.code = code;
+ this.evidence = evidence;
+ }
+}
+
+export function computeCorpusSha256(corpusBytes) {
+ return createHash('sha256').update(corpusBytes).digest('hex');
+}
+
+function incompatibleEvidence(now, failure, manifest = {}) {
+ return {
+ status: 'incompatible',
+ checkedAt: now().toISOString(),
+ ...(Number.isInteger(manifest.epoch) ? { epoch: manifest.epoch } : {}),
+ ...(typeof manifest.corpusSha256 === 'string' ? { corpusSha256: manifest.corpusSha256 } : {}),
+ ...(typeof manifest.deploymentSha === 'string'
+ ? { deploymentSha: manifest.deploymentSha }
+ : {}),
+ failure,
+ };
+}
+
+function fail(code, message, now, manifest, probeId) {
+ throw new ShareContractProbeError(
+ code,
+ message,
+ incompatibleEvidence(
+ now,
+ {
+ code,
+ ...(probeId === undefined ? {} : { probeId }),
+ },
+ manifest,
+ ),
+ );
+}
+
+function normalizeOrigin(origin) {
+ let parsed;
+ try {
+ parsed = new URL(origin);
+ } catch {
+ throw new Error('origin must be an absolute HTTP(S) URL');
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error('origin must use HTTP(S)');
+ }
+ if (
+ parsed.username !== '' ||
+ parsed.password !== '' ||
+ parsed.search !== '' ||
+ parsed.hash !== ''
+ ) {
+ throw new Error('origin must not contain credentials, a query, or a fragment');
+ }
+ parsed.pathname = parsed.pathname.replace(/\/+$/, '');
+ return parsed.href.replace(/\/$/, '');
+}
+
+function findFixedFixtures(corpus, now) {
+ if (!corpus || typeof corpus !== 'object' || !Array.isArray(corpus.validShares)) {
+ fail('corpus-malformed', 'fixture corpus has no validShares array', now);
+ }
+
+ return FIXED_PROBE_CASE_IDS.map((id) => {
+ const matches = corpus.validShares.filter((fixture) => fixture?.id === id);
+ if (matches.length !== 1) {
+ fail('corpus-fixed-probe-missing', `fixture corpus must contain exactly one ${id}`, now);
+ }
+ const fixture = matches[0];
+ if (
+ fixture.version !== 2 ||
+ typeof fixture.sharedUrl !== 'string' ||
+ typeof fixture.token !== 'string' ||
+ fixture.token.length === 0
+ ) {
+ fail('corpus-fixed-probe-malformed', `fixed probe fixture ${id} is malformed`, now);
+ }
+ return fixture;
+ });
+}
+
+async function fetchWithTimeout(fetchImpl, url) {
+ return fetchImpl(url, {
+ headers: { accept: 'application/json, text/html;q=0.9' },
+ redirect: 'follow',
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+}
+
+// Retry once on a network-level failure (fetch rejects — DNS, connection reset,
+// or the request-timeout AbortError) so a single CDN blip at the cron mark does
+// not page on-call for a fault that self-resolves next run. A non-ok HTTP
+// response does NOT reject, so 4xx/5xx stay immediate failures — only transport
+// faults retry.
+async function fetchWithRetry(fetchImpl, url) {
+ try {
+ return await fetchWithTimeout(fetchImpl, url);
+ } catch {
+ return fetchWithTimeout(fetchImpl, url);
+ }
+}
+
+async function readManifest(fetchImpl, origin, now) {
+ let response;
+ try {
+ response = await fetchWithRetry(fetchImpl, `${origin}${MANIFEST_PATH}`);
+ } catch {
+ fail('manifest-request-failed', 'manifest request failed', now);
+ }
+ if (!response.ok) {
+ fail('manifest-http-status', `manifest request returned ${response.status}`, now);
+ }
+
+ let raw;
+ try {
+ raw = await response.text();
+ } catch {
+ fail('manifest-read-failed', 'manifest response could not be read', now);
+ }
+
+ let manifest;
+ try {
+ manifest = JSON.parse(raw);
+ } catch {
+ fail('manifest-invalid-json', 'manifest is not valid JSON', now);
+ }
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
+ fail('manifest-invalid-shape', 'manifest must be a JSON object', now);
+ }
+ return manifest;
+}
+
+function validateManifest(manifest, expectedCorpusSha256, expectedDeploymentSha, now) {
+ if (!Number.isInteger(manifest.epoch) || manifest.epoch < REQUIRED_EPOCH) {
+ fail('manifest-epoch', `manifest epoch must be at least ${REQUIRED_EPOCH}`, now, manifest);
+ }
+ if (typeof manifest.corpusSha256 !== 'string' || !SHA256_PATTERN.test(manifest.corpusSha256)) {
+ fail('manifest-corpus-digest-shape', 'manifest corpusSha256 is malformed', now, manifest);
+ }
+ if (manifest.corpusSha256 !== expectedCorpusSha256) {
+ fail('manifest-corpus-digest-mismatch', 'manifest corpus digest does not match', now, manifest);
+ }
+ if (
+ typeof manifest.deploymentSha !== 'string' ||
+ !DEPLOYMENT_SHA_PATTERN.test(manifest.deploymentSha)
+ ) {
+ fail('manifest-deployment-sha-shape', 'manifest deploymentSha is malformed', now, manifest);
+ }
+ if (expectedDeploymentSha !== undefined && manifest.deploymentSha !== expectedDeploymentSha) {
+ fail(
+ 'manifest-deployment-sha-mismatch',
+ 'manifest deployment SHA does not match',
+ now,
+ manifest,
+ );
+ }
+}
+
+function decodeHtmlAttribute(value) {
+ return value
+ .replaceAll('&amp;', '&')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&#39;', "'")
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>');
+}
+
+function attribute(tag, name) {
+ const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const match = new RegExp(
+ `(?:^|\\s)${escapedName}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,
+ 'i',
+ ).exec(tag);
+ const value = match?.[1] ?? match?.[2] ?? match?.[3];
+ return value === undefined ? undefined : decodeHtmlAttribute(value);
+}
+
+function anchorHref(html, testId, now, manifest, probeId) {
+ const matches = [...html.matchAll(/<a\b[^>]*>/gi)]
+ .map((match) => match[0])
+ .filter((tag) => attribute(tag, 'data-testid') === testId);
+ if (matches.length !== 1) {
+ fail(
+ 'page-anchor-cardinality',
+ `probe ${probeId} must render exactly one ${testId} anchor`,
+ now,
+ manifest,
+ probeId,
+ );
+ }
+ const href = attribute(matches[0], 'href');
+ if (href === undefined) {
+ fail(
+ 'page-anchor-href-missing',
+ `probe ${probeId} ${testId} anchor has no href`,
+ now,
+ manifest,
+ probeId,
+ );
+ }
+ return href;
+}
+
+function assertDecodedSplash(html, fixture, manifest, now) {
+ if (!/<(?:h1|h2)\b[^>]*data-testid=(?:"splash-filename"|'splash-filename')[^>]*>/i.test(html)) {
+ fail(
+ 'page-decode-result',
+ `probe ${fixture.id} did not render the decoded splash`,
+ now,
+ manifest,
+ fixture.id,
+ );
+ }
+
+ const sourceHref = anchorHref(html, 'splash-repo-path', now, manifest, fixture.id);
+ if (sourceHref !== fixture.sharedUrl) {
+ fail(
+ 'page-source-href',
+ `probe ${fixture.id} source href is not canonical`,
+ now,
+ manifest,
+ fixture.id,
+ );
+ }
+
+ const customSchemeHref = anchorHref(html, 'splash-open-cta', now, manifest, fixture.id);
+ const expectedCustomSchemeHref = `openknowledge://share?token=${fixture.token}`;
+ if (customSchemeHref !== expectedCustomSchemeHref) {
+ fail(
+ 'page-custom-uri',
+ `probe ${fixture.id} custom URI is not the exact token-only handoff`,
+ now,
+ manifest,
+ fixture.id,
+ );
+ }
+}
+
+async function probePage(fetchImpl, origin, fixture, manifest, now) {
+ let response;
+ try {
+ response = await fetchWithRetry(fetchImpl, `${origin}/d/${fixture.token}`);
+ } catch {
+ fail('page-request-failed', `probe ${fixture.id} request failed`, now, manifest, fixture.id);
+ }
+ if (!response.ok) {
+ fail(
+ 'page-http-status',
+ `probe ${fixture.id} request returned ${response.status}`,
+ now,
+ manifest,
+ fixture.id,
+ );
+ }
+
+ let html;
+ try {
+ html = await response.text();
+ } catch {
+ fail(
+ 'page-read-failed',
+ `probe ${fixture.id} response could not be read`,
+ now,
+ manifest,
+ fixture.id,
+ );
+ }
+ assertDecodedSplash(html, fixture, manifest, now);
+ return { id: fixture.id, status: 'compatible' };
+}
+
+export async function probeShareContract({
+ origin,
+ corpus,
+ corpusBytes,
+ expectedDeploymentSha,
+ fetchImpl = fetch,
+ now = () => new Date(),
+}) {
+ const normalizedOrigin = normalizeOrigin(origin);
+ const fixtures = findFixedFixtures(corpus, now);
+ const expectedCorpusSha256 = computeCorpusSha256(corpusBytes);
+ const manifest = await readManifest(fetchImpl, normalizedOrigin, now);
+ validateManifest(manifest, expectedCorpusSha256, expectedDeploymentSha, now);
+
+ const probes = [];
+ for (const fixture of fixtures) {
+ probes.push(await probePage(fetchImpl, normalizedOrigin, fixture, manifest, now));
+ }
+
+ return {
+ status: 'compatible',
+ checkedAt: now().toISOString(),
+ epoch: manifest.epoch,
+ corpusSha256: manifest.corpusSha256,
+ deploymentSha: manifest.deploymentSha,
+ probes,
+ };
+}
+
+function parseArgs(argv) {
+ const values = new Map();
+ for (let index = 0; index < argv.length; index += 2) {
+ const key = argv[index];
+ const value = argv[index + 1];
+ if (!key?.startsWith('--') || value === undefined || value.startsWith('--')) {
+ throw new Error(`invalid argument near ${key ?? '<end>'}`);
+ }
+ if (values.has(key)) throw new Error(`duplicate argument ${key}`);
+ values.set(key, value);
+ }
+
+ const allowed = new Set(['--origin', '--corpus', '--expected-deployment-sha', '--evidence']);
+ for (const key of values.keys()) {
+ if (!allowed.has(key)) throw new Error(`unknown argument ${key}`);
+ }
+ if (!values.has('--origin')) throw new Error('--origin is required');
+ if (!values.has('--evidence')) throw new Error('--evidence is required');
+ return values;
+}
+
+function writeEvidence(path, evidence) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, `${JSON.stringify(evidence, null, 2)}\n`, 'utf8');
+}
+
+async function main() {
+ const values = parseArgs(process.argv.slice(2));
+ const scriptDirectory = dirname(fileURLToPath(import.meta.url));
+ const corpusPath = resolve(
+ values.get('--corpus') ??
+ join(scriptDirectory, '../../test-support/fixtures/share-url-v1-v2.json'),
+ );
+ const evidencePath = resolve(values.get('--evidence'));
+ const now = () => new Date();
+
+ try {
+ const corpusBytes = readFileSync(corpusPath, 'utf8');
+ const corpus = JSON.parse(corpusBytes);
+ const evidence = await probeShareContract({
+ origin: values.get('--origin'),
+ corpus,
+ corpusBytes,
+ expectedDeploymentSha: values.get('--expected-deployment-sha'),
+ now,
+ });
+ writeEvidence(evidencePath, evidence);
+ console.log(
+ `share-contract probe compatible: epoch=${evidence.epoch} deployment=${evidence.deploymentSha}`,
+ );
+ } catch (error) {
+ const evidence =
+ error instanceof ShareContractProbeError
+ ? error.evidence
+ : incompatibleEvidence(now, { code: 'probe-internal-error' });
+ writeEvidence(evidencePath, evidence);
+ const message = error instanceof Error ? error.message : 'unknown probe failure';
+ console.error(`share-contract probe incompatible: ${message}`);
+ process.exitCode = 1;
+ }
+}
+
+const invokedPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : '';
+if (invokedPath === import.meta.url) {
+ await main();
+}
diff --git a/.github/scripts/probe-share-contract.test.mjs b/.github/scripts/probe-share-contract.test.mjs
new file mode 100644
index 000000000..c7f8574a0
--- /dev/null
+++ b/.github/scripts/probe-share-contract.test.mjs
@@ -0,0 +1,249 @@
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { createServer } from 'node:http';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ computeCorpusSha256,
+ FIXED_PROBE_CASE_IDS,
+ probeShareContract,
+} from './probe-share-contract.mjs';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const CORPUS_BYTES = readFileSync(
+ join(REPO_ROOT, 'test-support/fixtures/share-url-v1-v2.json'),
+ 'utf8',
+);
+const CORPUS = JSON.parse(CORPUS_BYTES);
+const EXPECTED_DEPLOYMENT_SHA = '1234567890abcdef1234567890abcdef12345678';
+
+const fixedCases = FIXED_PROBE_CASE_IDS.map((id) => {
+ const fixture = CORPUS.validShares.find((candidate) => candidate.id === id);
+ if (!fixture) throw new Error(`missing fixed probe fixture ${id}`);
+ return fixture;
+});
+
+const servers = [];
+
+afterEach(async () => {
+ await Promise.all(
+ servers.splice(0).map(
+ (server) =>
+ new Promise((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ }),
+ ),
+ );
+});
+
+function htmlFor(fixture, overrides = {}) {
+ const sourceHref = overrides.sourceHref ?? fixture.sharedUrl;
+ const customSchemeHref =
+ overrides.customSchemeHref ?? `openknowledge://share?token=${fixture.token}`;
+ const expectedName =
+ fixture.target.kind === 'folder' && fixture.target.folderPath === ''
+ ? new URL(fixture.sharedUrl).pathname.split('/')[2]
+ : decodeURIComponent(new URL(fixture.sharedUrl).pathname.split('/').at(-1));
+ return `<!doctype html><html><body>
+ <h1 data-testid="splash-filename"><a href="${sourceHref}">${expectedName}</a></h1>
+ <a data-testid="splash-repo-path" href="${sourceHref}">source</a>
+ <a href="${customSchemeHref}" data-testid="splash-open-cta">open</a>
+ </body></html>`;
+}
+
+async function startReader({ manifest, pages = new Map(), malformedManifest = false } = {}) {
+ const server = createServer((request, response) => {
+ if (request.url === '/.well-known/openknowledge-share-contract.json') {
+ if (manifest === undefined) {
+ response.writeHead(404).end('missing');
+ return;
+ }
+ response.setHeader('content-type', 'application/json');
+ response.end(malformedManifest ? '{' : JSON.stringify(manifest));
+ return;
+ }
+
+ const page = pages.get(request.url);
+ if (page === undefined) {
+ response.writeHead(404).end('missing');
+ return;
+ }
+ response.setHeader('content-type', 'text/html; charset=utf-8');
+ response.end(page);
+ });
+ servers.push(server);
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (typeof address === 'string' || address === null) throw new Error('missing listener port');
+ return `http://127.0.0.1:${address.port}`;
+}
+
+function compatibleReader(overrides = {}) {
+ const pages = new Map(fixedCases.map((fixture) => [`/d/${fixture.token}`, htmlFor(fixture)]));
+ return {
+ manifest: {
+ epoch: 2,
+ corpusSha256: computeCorpusSha256(CORPUS_BYTES),
+ deploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ ...overrides.manifest,
+ },
+ pages: overrides.pages ?? pages,
+ malformedManifest: overrides.malformedManifest,
+ };
+}
+
+async function expectProbeFailure(reader, message) {
+ const origin = await startReader(reader);
+ await expect(
+ probeShareContract({
+ origin,
+ corpus: CORPUS,
+ corpusBytes: CORPUS_BYTES,
+ expectedDeploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ }),
+ ).rejects.toThrow(message);
+}
+
+describe('share-contract reader probe', () => {
+ test('proves the fixed v2 document and content-root pages against the manifest', async () => {
+ const origin = await startReader(compatibleReader());
+ const evidence = await probeShareContract({
+ origin,
+ corpus: CORPUS,
+ corpusBytes: CORPUS_BYTES,
+ expectedDeploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ now: () => new Date('2026-08-13T12:00:00.000Z'),
+ });
+
+ expect(evidence).toMatchObject({
+ status: 'compatible',
+ epoch: 2,
+ corpusSha256: computeCorpusSha256(CORPUS_BYTES),
+ deploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ checkedAt: '2026-08-13T12:00:00.000Z',
+ probes: FIXED_PROBE_CASE_IDS.map((id) => ({ id, status: 'compatible' })),
+ });
+ const serialized = JSON.stringify(evidence);
+ for (const fixture of fixedCases) {
+ expect(serialized).not.toContain(fixture.token);
+ expect(serialized).not.toContain(fixture.sharedUrl);
+ }
+ });
+
+ test('retries once past a transient network blip on the first fetch', async () => {
+ const origin = await startReader(compatibleReader());
+ let attempts = 0;
+ const flakyFetch = (url, init) => {
+ attempts += 1;
+ if (attempts === 1) return Promise.reject(new TypeError('transient network blip'));
+ return fetch(url, init);
+ };
+ const evidence = await probeShareContract({
+ origin,
+ corpus: CORPUS,
+ corpusBytes: CORPUS_BYTES,
+ expectedDeploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ fetchImpl: flakyFetch,
+ });
+ expect(evidence.status).toBe('compatible');
+ // The blip on the first attempt was retried rather than paged on.
+ expect(attempts).toBeGreaterThan(1);
+ });
+
+ test('fails closed when the network fault persists past the single retry', async () => {
+ const origin = await startReader(compatibleReader());
+ const alwaysThrows = () => Promise.reject(new TypeError('persistent network fault'));
+ await expect(
+ probeShareContract({
+ origin,
+ corpus: CORPUS,
+ corpusBytes: CORPUS_BYTES,
+ expectedDeploymentSha: EXPECTED_DEPLOYMENT_SHA,
+ fetchImpl: alwaysThrows,
+ }),
+ ).rejects.toThrow(/manifest request failed/);
+ });
+
+ test.each([
+ ['missing manifest', {}, /manifest request returned 404/],
+ [
+ 'malformed manifest',
+ compatibleReader({ malformedManifest: true }),
+ /manifest is not valid JSON/,
+ ],
+ ['wrong epoch', compatibleReader({ manifest: { epoch: 1 } }), /manifest epoch/],
+ [
+ 'wrong corpus digest',
+ compatibleReader({ manifest: { corpusSha256: '0'.repeat(64) } }),
+ /corpus digest/,
+ ],
+ [
+ 'missing deployment SHA',
+ compatibleReader({ manifest: { deploymentSha: undefined } }),
+ /deploymentSha/,
+ ],
+ [
+ 'wrong deployment SHA',
+ compatibleReader({ manifest: { deploymentSha: 'f'.repeat(40) } }),
+ /deployment SHA/,
+ ],
+ ])('fails closed on %s', async (_name, reader, message) => {
+ await expectProbeFailure(reader, message);
+ });
+
+ test('fails when the document page source anchor is not the canonical source URL', async () => {
+ const pages = compatibleReader().pages;
+ const documentFixture = fixedCases[0];
+ pages.set(
+ `/d/${documentFixture.token}`,
+ htmlFor(documentFixture, {
+ sourceHref:
+ 'https://github.com/inkeep/open-knowledge/blob/main/modules/backend-libraries.md',
+ }),
+ );
+ await expectProbeFailure(compatibleReader({ pages }), /source href/);
+ });
+
+ test('fails when the content-root page custom handoff is not the exact token-only URI', async () => {
+ const pages = compatibleReader().pages;
+ const contentRootFixture = fixedCases[1];
+ pages.set(
+ `/d/${contentRootFixture.token}`,
+ htmlFor(contentRootFixture, {
+ customSchemeHref: `openknowledge://share?url=${encodeURIComponent(contentRootFixture.sharedUrl)}`,
+ }),
+ );
+ await expectProbeFailure(compatibleReader({ pages }), /custom URI/);
+ });
+
+ test('the CLI writes bounded incompatible evidence before exiting non-zero', () => {
+ const directory = mkdtempSync(join(tmpdir(), 'share-contract-probe-'));
+ const evidencePath = join(directory, 'evidence.json');
+ try {
+ const result = spawnSync(
+ process.execPath,
+ [
+ join(REPO_ROOT, '.github/scripts/probe-share-contract.mjs'),
+ '--origin',
+ 'http://127.0.0.1:1',
+ '--evidence',
+ evidencePath,
+ ],
+ { encoding: 'utf8' },
+ );
+
+ expect(result.status).toBe(1);
+ expect(JSON.parse(readFileSync(evidencePath, 'utf8'))).toMatchObject({
+ status: 'incompatible',
+ failure: { code: 'manifest-request-failed' },
+ });
+ const evidence = readFileSync(evidencePath, 'utf8');
+ expect(evidence).not.toContain('127.0.0.1');
+ for (const fixture of fixedCases) expect(evidence).not.toContain(fixture.token);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/.github/scripts/share-contract-cache-shape.test.mjs b/.github/scripts/share-contract-cache-shape.test.mjs
new file mode 100644
index 000000000..45b220f53
--- /dev/null
+++ b/.github/scripts/share-contract-cache-shape.test.mjs
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+describe('share contract corpus cache wiring', () => {
+ test('the nested cross-release oracle invalidates every Turbo task cache', () => {
+ const turbo = JSON.parse(readFileSync(join(REPO_ROOT, 'turbo.json'), 'utf8'));
+ const corpusPath = 'test-support/fixtures/share-url-v1-v2.json';
+
+ expect(turbo.globalDependencies).toContain(corpusPath);
+ expect(turbo.globalDependencies.filter((entry) => entry === corpusPath)).toHaveLength(1);
+ });
+
+ test('the static docs manifest deployment identity invalidates the docs build cache', () => {
+ const turbo = JSON.parse(readFileSync(join(REPO_ROOT, 'turbo.json'), 'utf8'));
+ const docsBuild = turbo.tasks['@inkeep/open-knowledge-docs#build'];
+
+ expect(docsBuild.env).toEqual(['VERCEL_GIT_COMMIT_SHA', 'GITHUB_SHA']);
+ });
+});
diff --git a/.github/scripts/share-contract-monitor-shape.test.mjs b/.github/scripts/share-contract-monitor-shape.test.mjs
new file mode 100644
index 000000000..6518ab484
--- /dev/null
+++ b/.github/scripts/share-contract-monitor-shape.test.mjs
@@ -0,0 +1,76 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const WORKFLOW_PATH = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '..',
+ 'workflows',
+ 'share-contract-monitor.yml',
+);
+const workflow = readFileSync(WORKFLOW_PATH, 'utf8');
+const REGRESSION_HANDLER_CONDITION = "if: always() && steps.probe.outcome == 'failure'";
+
+function count(source, pattern) {
+ return [...source.matchAll(pattern)].length;
+}
+
+function assertRegressionHandlersStayReachable(source) {
+ const guardedCount = count(source, /^\s+if: always\(\) && steps\.probe\.outcome == 'failure'$/gm);
+ if (guardedCount !== 3) {
+ throw new Error(`expected 3 status-guarded regression handlers, found ${guardedCount}`);
+ }
+}
+
+describe('share contract production monitor workflow', () => {
+ test('runs on a schedule and manual dispatch without release-writing authority', () => {
+ expect(workflow).toContain('schedule:');
+ expect(workflow).toContain('workflow_dispatch:');
+ expect(workflow).toContain('actions: read');
+ expect(workflow).toContain('contents: read');
+ expect(workflow).not.toMatch(/contents:\s*write/);
+ expect(workflow).not.toMatch(/packages:\s*write/);
+ expect(workflow).not.toContain('repository_dispatch');
+ });
+
+ test('the structural guard catches workflow wiring absence', () => {
+ const withoutSchedule = workflow.replace(' schedule:\n', '');
+ const withoutProbe = workflow.replace(
+ 'node .github/scripts/probe-share-contract.mjs',
+ 'node .github/scripts/other.mjs',
+ );
+
+ expect(withoutSchedule).not.toContain('schedule:');
+ expect(count(withoutProbe, /node \.github\/scripts\/probe-share-contract\.mjs/g)).toBe(0);
+ });
+
+ test('uses the shared probe against production and uploads evidence on every outcome', () => {
+ expect(count(workflow, /node \.github\/scripts\/probe-share-contract\.mjs/g)).toBe(1);
+ expect(workflow).toContain('https://openknowledge.ai');
+ expect(workflow).toContain('test-support/fixtures/share-url-v1-v2.json');
+ expect(workflow).toContain('continue-on-error: true');
+ expect(workflow).toContain('if: always()');
+ expect(workflow).toContain('actions/upload-artifact@');
+ expect(workflow).toContain('share-contract-evidence');
+ });
+
+ test('fails after alerting and retrieves last-compatible evidence only on regression', () => {
+ assertRegressionHandlersStayReachable(workflow);
+ expect(workflow).toContain('gh run list');
+ expect(workflow).toContain('gh run download');
+ expect(workflow).toContain('SLACK_RELEASES_WEBHOOK_URL');
+ expect(workflow).toContain('exit 1');
+ });
+
+ test('rejects a regression handler that drops the explicit status override', () => {
+ const withoutAlways = workflow.replace(
+ REGRESSION_HANDLER_CONDITION,
+ "if: steps.probe.outcome == 'failure'",
+ );
+
+ expect(() => assertRegressionHandlersStayReachable(withoutAlways)).toThrow(
+ 'expected 3 status-guarded regression handlers, found 2',
+ );
+ });
+});
diff --git a/.github/workflows/share-contract-monitor.yml b/.github/workflows/share-contract-monitor.yml
new file mode 100644
index 000000000..21c793b22
--- /dev/null
+++ b/.github/workflows/share-contract-monitor.yml
@@ -0,0 +1,107 @@
+name: Share contract production monitor
+
+on:
+ schedule:
+ - cron: "17,47 * * * *"
+ workflow_dispatch:
+
+permissions:
+ actions: read
+ contents: read
+
+concurrency:
+ group: share-contract-production-monitor
+ cancel-in-progress: false
+
+jobs:
+ probe:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Node
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: "24"
+
+ - name: Probe production reader contract
+ id: probe
+ continue-on-error: true
+ run: |
+ set -euo pipefail
+ node .github/scripts/probe-share-contract.mjs \
+ --origin https://openknowledge.ai \
+ --corpus test-support/fixtures/share-url-v1-v2.json \
+ --evidence "$RUNNER_TEMP/share-contract-evidence.json"
+
+ - name: Upload reader-contract evidence
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: share-contract-evidence
+ path: ${{ runner.temp }}/share-contract-evidence.json
+ retention-days: 30
+ if-no-files-found: error
+
+ - name: Resolve last compatible deployment
+ id: last-compatible
+ if: always() && steps.probe.outcome == 'failure'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -euo pipefail
+ last_run=$(gh run list \
+ --workflow=share-contract-monitor.yml \
+ --status=success \
+ --limit=1 \
+ --json databaseId \
+ --jq '.[0].databaseId // empty')
+ deployment=unavailable
+ if [[ -n "$last_run" ]]; then
+ mkdir -p "$RUNNER_TEMP/last-compatible"
+ if gh run download "$last_run" \
+ --name share-contract-evidence \
+ --dir "$RUNNER_TEMP/last-compatible"; then
+ candidate=$(jq -r '.deploymentSha // empty' \
+ "$RUNNER_TEMP/last-compatible/share-contract-evidence.json")
+ if [[ "$candidate" =~ ^[0-9a-f]{40}$ ]]; then
+ deployment="$candidate"
+ fi
+ fi
+ fi
+ echo "deployment_sha=$deployment" >> "$GITHUB_OUTPUT"
+
+ - name: Alert on reader-contract regression
+ if: always() && steps.probe.outcome == 'failure'
+ env:
+ LAST_COMPATIBLE_SHA: ${{ steps.last-compatible.outputs.deployment_sha }}
+ SLACK_RELEASES_WEBHOOK_URL: ${{ secrets.SLACK_RELEASES_WEBHOOK_URL }}
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
+ run: |
+ set -uo pipefail
+ RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
+ TEXT="Open Knowledge share-contract v2 production probe failed. Last compatible deployment: ${LAST_COMPATIBLE_SHA:-unavailable}. Repair forward or select that compatible deployment; do not roll back below epoch 2. ${RUN_URL}"
+ echo "## Share-contract v2 regression" >> "$GITHUB_STEP_SUMMARY"
+ echo "Last compatible deployment: \`${LAST_COMPATIBLE_SHA:-unavailable}\`" >> "$GITHUB_STEP_SUMMARY"
+ echo "Run: ${RUN_URL}" >> "$GITHUB_STEP_SUMMARY"
+
+ WEBHOOK_URL="${SLACK_RELEASES_WEBHOOK_URL:-${SLACK_WEBHOOK_URL:-}}"
+ if [[ -z "$WEBHOOK_URL" ]]; then
+ echo "::warning::No Slack webhook secret is configured; the workflow failure remains the alert."
+ exit 0
+ fi
+ payload=$(jq -nc --arg text "$TEXT" '{text: $text}')
+ if ! curl -sS --fail --connect-timeout 10 --max-time 30 -X POST \
+ -H 'Content-type: application/json' \
+ --data "$payload" \
+ "$WEBHOOK_URL"; then
+ echo "::warning::Share-contract regression alert failed to POST."
+ fi
+
+ - name: Fail the incompatible production probe
+ if: always() && steps.probe.outcome == 'failure'
+ run: exit 1
diff --git a/docs/src/app/.well-known/openknowledge-share-contract.json/route.ts b/docs/src/app/.well-known/openknowledge-share-contract.json/route.ts
new file mode 100644
index 000000000..7a472239a
--- /dev/null
+++ b/docs/src/app/.well-known/openknowledge-share-contract.json/route.ts
@@ -0,0 +1,16 @@
+import { buildShareContractManifest } from '@/lib/share-contract-manifest';
+
+export const dynamic = 'force-static';
+
+// The share-contract production monitor polls this manifest to detect a
+// reader-contract regression, so it must never read a stale copy: max-age=0 +
+// must-revalidate forces revalidation on every fetch. (The sibling
+// apple-app-site-association manifest is the opposite — it caches aggressively
+// because Apple polls it rarely and tolerates staleness.)
+const CACHE_CONTROL = 'public, max-age=0, must-revalidate';
+
+export function GET(): Response {
+ return Response.json(buildShareContractManifest(), {
+ headers: { 'Cache-Control': CACHE_CONTROL },
+ });
+}
diff --git a/docs/src/app/d/[encoded]/download/route.test.ts b/docs/src/app/d/[encoded]/download/route.test.ts
index 0ebdb379b..e5ab5ec55 100644
--- a/docs/src/app/d/[encoded]/download/route.test.ts
+++ b/docs/src/app/d/[encoded]/download/route.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test, vi } from 'vitest';
+import fixture from '../../../../../../test-support/fixtures/share-url-v1-v2.json';
const SPLASH_URL =
'https://github.com/inkeep/open-knowledge/releases/latest/download/OpenKnowledge-arm64.dmg';
@@ -21,14 +22,27 @@ vi.doMock('../../../../lib/track.ts', () => ({
// Flip the decoded-share outcome per test.
let _viewKind: 'ok' | 'invalid' | 'unsupported-version' = 'ok';
-vi.doMock('../../../../lib/share-splash.ts', () => ({
- buildSplashViewModel: () => ({ kind: _viewKind }),
- SPLASH_DOWNLOAD_URL: SPLASH_URL,
-}));
+let _useRealShareContract = false;
+vi.doMock('../../../../lib/share-splash.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../../lib/share-splash.ts')>();
+ return {
+ ...actual,
+ buildSplashViewModel: (encoded: string) =>
+ _useRealShareContract ? actual.buildSplashViewModel(encoded) : { kind: _viewKind },
+ SPLASH_DOWNLOAD_URL: SPLASH_URL,
+ };
+});
-vi.doMock('../../../../lib/deferred-share.ts', () => ({
- buildPendingShareCookie: (encoded: string) => ({ name: 'ok-pending-share', value: encoded }),
-}));
+vi.doMock('../../../../lib/deferred-share.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../../lib/deferred-share.ts')>();
+ return {
+ ...actual,
+ buildPendingShareCookie: (encoded: string) =>
+ _useRealShareContract
+ ? actual.buildPendingShareCookie(encoded)
+ : { name: 'ok-pending-share', value: encoded },
+ };
+});
const { GET } = await import('./route.ts');
@@ -39,6 +53,30 @@ function call(encoded: string, query = ''): Promise<Response> {
}
describe('GET /d/[encoded]/download', () => {
+ test('maximum canonical v2 share crosses the real decoder and cookie builder', async () => {
+ const canonicalV2 = fixture.bounds.maxCase;
+ expect(canonicalV2.token).toHaveLength(3984);
+
+ _useRealShareContract = true;
+ _lastCapture = null;
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-13T00:00:00.000Z'));
+ try {
+ const res = await call(canonicalV2.token);
+ const cookie = res.headers.get('set-cookie');
+
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe(SPLASH_URL);
+ expect(cookie).toBe(
+ `ok_pending_share=${canonicalV2.token}; Path=/; Expires=Thu, 20 Aug 2026 00:00:00 GMT; Max-Age=604800; Secure; HttpOnly; SameSite=lax`,
+ );
+ expect(_lastCapture?.event).toBe('dmg_downloaded');
+ } finally {
+ _useRealShareContract = false;
+ vi.useRealTimers();
+ }
+ });
+
test('picker request carries a valid share to the architecture picker', async () => {
_viewKind = 'ok';
_lastCapture = null;
diff --git a/docs/src/lib/deferred-share.test.ts b/docs/src/lib/deferred-share.test.ts
index efdccba9c..523d6821f 100644
--- a/docs/src/lib/deferred-share.test.ts
+++ b/docs/src/lib/deferred-share.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test } from 'vitest';
+import fixture from '../../../test-support/fixtures/share-url-v1-v2.json';
import {
buildPendingShareCookie,
decideContinue,
@@ -24,6 +25,40 @@ describe('buildPendingShareCookie', () => {
});
describe('decideContinue — redeem branch', () => {
+ test('carries the maximum canonical v2 token opaquely and rejects one byte over its bound', () => {
+ const accepted = decideContinue({
+ cookieToken: fixture.bounds.maxCase.token,
+ port: '52431',
+ nonce: VALID_NONCE,
+ });
+ expect(accepted.kind).toBe('redeem');
+ if (accepted.kind === 'redeem') {
+ expect(new URL(accepted.location).searchParams.get('token')).toBe(
+ fixture.bounds.maxCase.token,
+ );
+ }
+
+ expect(
+ decideContinue({
+ cookieToken: fixture.bounds.overLimitToken,
+ port: '52431',
+ nonce: VALID_NONCE,
+ }),
+ ).toEqual({ kind: 'welcome', clearCookie: true });
+ });
+
+ test('retains the historical v1 handoff ceiling', () => {
+ const atLimit = `AQ${'A'.repeat(4094)}`;
+ const overLimit = `${atLimit}A`;
+ expect(decideContinue({ cookieToken: atLimit, port: '52431', nonce: VALID_NONCE }).kind).toBe(
+ 'redeem',
+ );
+ expect(decideContinue({ cookieToken: overLimit, port: '52431', nonce: VALID_NONCE })).toEqual({
+ kind: 'welcome',
+ clearCookie: true,
+ });
+ });
+
test('redirects the pending token to the loopback listener when all inputs are valid', () => {
const decision = decideContinue({
cookieToken: VALID_TOKEN,
diff --git a/docs/src/lib/deferred-share.ts b/docs/src/lib/deferred-share.ts
index 72ac18c3c..6e7cfe373 100644
--- a/docs/src/lib/deferred-share.ts
+++ b/docs/src/lib/deferred-share.ts
@@ -44,7 +44,8 @@ const REDEEM_PATH = '/redeem';
* a few hundred base64url chars; anything larger is hostile or corrupt and is
* dropped before it reaches the redirect builder.
*/
-const MAX_TOKEN_LENGTH = 4096;
+const MAX_LEGACY_TOKEN_LENGTH = 4096;
+const MAX_V2_TOKEN_LENGTH = 3984;
/** Loopback ephemeral port range (OS-assigned). */
const MIN_PORT = 1;
@@ -79,7 +80,18 @@ export function buildPendingShareCookie(token: string): PendingShareCookieInit {
}
function isValidToken(token: string): boolean {
- return token.length > 0 && token.length <= MAX_TOKEN_LENGTH && BASE64URL_RE.test(token);
+ if (token.length === 0) return false;
+ const maxLength = peekShareVersion(token) === 2 ? MAX_V2_TOKEN_LENGTH : MAX_LEGACY_TOKEN_LENGTH;
+ return token.length <= maxLength && BASE64URL_RE.test(token);
+}
+
+function peekShareVersion(token: string): number | null {
+ if (token.length < 2) return null;
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
+ const first = alphabet.indexOf(token[0]);
+ const second = alphabet.indexOf(token[1]);
+ if (first < 0 || second < 0) return null;
+ return (first << 2) | (second >>> 4);
}
function isValidPort(port: string | null): port is string {
diff --git a/docs/src/lib/share-contract-manifest.test.ts b/docs/src/lib/share-contract-manifest.test.ts
new file mode 100644
index 000000000..1c8172ea7
--- /dev/null
+++ b/docs/src/lib/share-contract-manifest.test.ts
@@ -0,0 +1,29 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
+import {
+ buildShareContractManifest,
+ SHARE_CONTRACT_CORPUS_SHA256,
+} from './share-contract-manifest';
+
+describe('share contract manifest', () => {
+ test('attests the v2 epoch, checked-in fixture corpus, and Vercel deployment commit', async () => {
+ const deploymentSha = '1234567890abcdef1234567890abcdef12345678';
+ const corpusBytes = readFileSync(
+ new URL('../../../test-support/fixtures/share-url-v1-v2.json', import.meta.url),
+ );
+
+ expect(buildShareContractManifest({ VERCEL_GIT_COMMIT_SHA: deploymentSha })).toEqual({
+ epoch: 2,
+ corpusSha256: SHARE_CONTRACT_CORPUS_SHA256,
+ deploymentSha,
+ });
+ expect(SHARE_CONTRACT_CORPUS_SHA256).toBe(
+ createHash('sha256').update(corpusBytes).digest('hex'),
+ );
+ });
+
+ test('advertises an unusable deployment marker when no build commit is available', () => {
+ expect(buildShareContractManifest({}).deploymentSha).toBe('unavailable');
+ });
+});
diff --git a/docs/src/lib/share-contract-manifest.ts b/docs/src/lib/share-contract-manifest.ts
new file mode 100644
index 000000000..7156569e0
--- /dev/null
+++ b/docs/src/lib/share-contract-manifest.ts
@@ -0,0 +1,33 @@
+const SHARE_CONTRACT_EPOCH = 2;
+export const SHARE_CONTRACT_CORPUS_SHA256 =
+ 'e4f5bde6115efe82322865d7467de6be9a0eff47bb0dd5dc49f14a7df7dbce82';
+
+/**
+ * Public reader-contract manifest served at
+ * `/.well-known/openknowledge-share-contract.json` and polled by the
+ * share-contract production monitor (`.github/workflows/share-contract-monitor.yml`).
+ *
+ * - `epoch` — the reader-contract generation. The monitor fails if production
+ * ever serves an epoch below the one it requires (a backward-incompatible
+ * rollback of the share-URL reader).
+ * - `corpusSha256` — SHA-256 of the frozen `share-url-v1-v2.json` fixture the
+ * monitor decodes against, so corpus/reader drift surfaces as a digest
+ * mismatch rather than a silent behavior change.
+ * - `deploymentSha` — the commit the live manifest was built from; names the
+ * last-compatible deployment when the monitor alerts.
+ */
+export interface ShareContractManifest {
+ epoch: typeof SHARE_CONTRACT_EPOCH;
+ corpusSha256: string;
+ deploymentSha: string;
+}
+
+export function buildShareContractManifest(
+ environment: Readonly<Record<string, string | undefined>> = process.env,
+): ShareContractManifest {
+ return {
+ epoch: SHARE_CONTRACT_EPOCH,
+ corpusSha256: SHARE_CONTRACT_CORPUS_SHA256,
+ deploymentSha: environment.VERCEL_GIT_COMMIT_SHA ?? environment.GITHUB_SHA ?? 'unavailable',
+ };
+}
diff --git a/docs/src/lib/share-splash.test.ts b/docs/src/lib/share-splash.test.ts
index 7f3de5507..60c9c119c 100644
--- a/docs/src/lib/share-splash.test.ts
+++ b/docs/src/lib/share-splash.test.ts
@@ -1,5 +1,6 @@
import { encodeShareUrl, KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
+import fixture from '../../../test-support/fixtures/share-url-v1-v2.json';
import { STABLE_DMG_URL } from './download-links.ts';
import { resolveTargetFromParams } from './download-targets.ts';
import {
@@ -33,20 +34,59 @@ function encodeV1(sharedUrl: string): string {
}
/**
- * Hand-rolled base64url for the NEGATIVE-path tests below — needed only
- * for forging v2-shaped payloads or other malformed bytes that the
- * production encoder can't be coaxed into emitting. Never used on the
- * happy path.
+ * The content-relative basename the splash renders for a v2 fixture: the last
+ * segment of the doc/folder path, or the repo name when a folder share targets
+ * the content root (empty path). Derived independently from the fixture's own
+ * `target`/`sharedUrl` so a byte-order swap or off-by-one in the v2 depth decode
+ * — a distinct code path from the v1 URL parse — surfaces as a filename mismatch.
*/
-function uint8ArrayToBase64Url(bytes: Uint8Array): string {
- let binaryString = '';
- for (let i = 0; i < bytes.length; i++) {
- binaryString += String.fromCharCode(bytes[i]);
- }
- return btoa(binaryString).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+function expectedContentFilename(entry: (typeof fixture.validShares)[number]): string {
+ const target: { docPath?: string; folderPath?: string } = entry.target;
+ const contentPath = target.docPath ?? target.folderPath ?? '';
+ const segments = contentPath.split('/').filter((segment) => segment.length > 0);
+ const basename = segments[segments.length - 1];
+ if (basename !== undefined) return basename;
+ const [, repo] = new URL(entry.sharedUrl).pathname.split('/').filter(Boolean);
+ return repo ?? '';
}
describe('buildSplashViewModel', () => {
+ test.each(
+ fixture.validShares.filter((entry) => entry.version === 2),
+ )('decodes canonical $id and hands the unchanged token to the desktop', (entry) => {
+ const view = buildSplashViewModel(entry.token);
+ expect(view).toMatchObject({
+ kind: 'ok',
+ sharedUrl: entry.sharedUrl,
+ githubUrl: entry.sharedUrl,
+ customSchemeUrl: `openknowledge://share?token=${entry.token}`,
+ target: entry.target.kind,
+ filename: expectedContentFilename(entry),
+ });
+ });
+
+ test.each(fixture.invalidTokens)('rejects canonical fixture case $id', (entry) => {
+ expect(buildSplashViewModel(entry.token)).toEqual({ kind: 'invalid' });
+ });
+
+ test.each(fixture.legacyAliases)('preserves tolerated v1 alias $id', (entry) => {
+ expect(buildSplashViewModel(entry.token)).toMatchObject({
+ kind: 'ok',
+ sharedUrl: entry.sharedUrl,
+ });
+ });
+
+ test('rejects an oversized v2 token as invalid before decoding', () => {
+ expect(buildSplashViewModel(fixture.bounds.overLimitToken)).toEqual({ kind: 'invalid' });
+ });
+
+ test('retains historical v1 decoding beyond the v2 token ceiling', () => {
+ const sharedUrl = `https://github.com/o/r/blob/main/${'a'.repeat(4000)}.md`;
+ const token = encodeV1(sharedUrl);
+ expect(token.length).toBeGreaterThan(fixture.bounds.maxV2TokenChars);
+ expect(buildSplashViewModel(token)).toMatchObject({ kind: 'ok', sharedUrl });
+ });
+
test('decodes a happy-path encoded blob URL into the ok view', () => {
const blobUrl = 'https://github.com/inkeep/playbooks/blob/main/marketing-playbook.md';
const encoded = encodeV1(blobUrl);
@@ -219,12 +259,12 @@ describe('buildSplashViewModel', () => {
}
});
- test('returns `unsupported-version` for a v2-shaped payload', () => {
- const blobBytes = new TextEncoder().encode('https://github.com/o/r/blob/main/file.md');
- const v2 = new Uint8Array([0x02, ...blobBytes]);
- const encoded = uint8ArrayToBase64Url(v2);
- const view = buildSplashViewModel(encoded);
- expect(view).toEqual({ kind: 'unsupported-version', version: 2 });
+ test('returns `unsupported-version` for a future payload', () => {
+ const future = fixture.unsupportedTokens[0];
+ expect(buildSplashViewModel(future.token)).toEqual({
+ kind: 'unsupported-version',
+ version: future.version,
+ });
});
test('returns `invalid` for undecodable base64url input', () => {
diff --git a/docs/src/lib/share-splash.ts b/docs/src/lib/share-splash.ts
index b0d6abe54..36e941f6b 100644
--- a/docs/src/lib/share-splash.ts
+++ b/docs/src/lib/share-splash.ts
@@ -2,9 +2,8 @@
* Splash-local mirrors of the pure functions that live in the OK workspace:
*
* - `decodeShareUrl` mirrors `packages/core/src/sharing/share-url.ts`
- * (v1 payload = `[0x01] || utf-8(<github-url>)`, base64url-encoded,
- * with tolerance for trailing `?query` and `#fragment`; decoded field is
- * `sharedUrl` — a blob URL for a doc share, a tree URL for a folder share)
+ * (permanent v1 payload = `[0x01] || utf-8(<github-url>)`; canonical v2 =
+ * `[0x02] || uint16be(contentRootDepth) || utf-8(<github-url>)`)
* - `parseGitHubShareUrl` / `parseGitHubBlobUrl` / `parseGitHubTreeUrl`
* mirror `packages/cli/src/github/url.ts` — the dispatcher returns a
* kind-discriminated `{kind:'doc'|'folder', owner, repo, branch, path}`
@@ -16,8 +15,8 @@
* build does NOT pull in the CRDT/markdown/Tiptap/CLI dependency tree. The
* duplication is bounded and pinned by `share-splash.test.ts`. Any wire change
* to the source modules (codec field names, URL-parser shapes) must be
- * mirrored here in lock-step — today that covers the `sharedUrl` field and
- * tree (folder) URL parsing.
+ * mirrored here in lock-step, including strict v2 canonical parsing and its
+ * token/payload/URL bounds.
*
* `buildSplashViewModel(encoded)` is the splash's single entry point — it
* folds the decoder + dispatcher into a discriminated `SplashView` the route
@@ -35,12 +34,32 @@ import {
import { SITE_NAME } from './site';
const SHARE_URL_VERSION_V1 = 0x01;
-
-interface DecodedShare {
- version: number;
- sharedUrl: string;
+const SHARE_URL_VERSION_V2 = 0x02;
+const V2_HEADER_BYTES = 3;
+const MAX_V2_SHARE_TOKEN_CHARS = 3984;
+const MAX_V2_SHARE_PAYLOAD_BYTES = 2988;
+const MAX_V2_SHARED_URL_UTF8_BYTES = 2985;
+const IPV4_AUTHORITY_PATTERN = /^(?:\d{1,3}\.){3}\d{1,3}$/;
+
+interface CanonicalGitHubShareSource {
+ host: string;
+ owner: string;
+ repo: string;
+ branch: string;
+ kind: 'doc' | 'folder';
+ targetSegments: string[];
}
+type DecodedShare =
+ | { version: 1; sharedUrl: string }
+ | {
+ version: 2;
+ sharedUrl: string;
+ contentRootDepth: number;
+ source: CanonicalGitHubShareSource;
+ targetPath: string;
+ };
+
class UnsupportedShareVersionError extends Error {
readonly version: number;
constructor(version: number) {
@@ -58,7 +77,18 @@ class InvalidShareUrlError extends Error {
}
function decodeShareUrl(encoded: string): DecodedShare {
- const cleaned = encoded.split(/[?#]/)[0];
+ const peekedVersion = peekBase64UrlVersion(encoded);
+ if (peekedVersion === SHARE_URL_VERSION_V2 && encoded.length > MAX_V2_SHARE_TOKEN_CHARS) {
+ throw new InvalidShareUrlError('Invalid v2 share token');
+ }
+
+ const suffixIndex = encoded.search(/[?#]/);
+ if (peekedVersion === SHARE_URL_VERSION_V2) {
+ if (suffixIndex !== -1) throw new InvalidShareUrlError('Invalid v2 share token');
+ return decodeV2ShareUrl(encoded);
+ }
+
+ const cleaned = suffixIndex === -1 ? encoded : encoded.slice(0, suffixIndex);
if (cleaned.length === 0) {
throw new InvalidShareUrlError('Share payload is empty');
}
@@ -87,7 +117,156 @@ function decodeShareUrl(encoded: string): DecodedShare {
throw new InvalidShareUrlError('Share payload body is not valid UTF-8');
}
- return { version, sharedUrl };
+ return { version: 1, sharedUrl };
+}
+
+function decodeV2ShareUrl(encoded: string): DecodedShare {
+ let bytes: Uint8Array;
+ try {
+ bytes = base64UrlToUint8Array(encoded);
+ } catch {
+ throw new InvalidShareUrlError('Share payload is not valid base64url');
+ }
+ if (
+ bytes.length <= V2_HEADER_BYTES ||
+ bytes.length > MAX_V2_SHARE_PAYLOAD_BYTES ||
+ uint8ArrayToBase64Url(bytes) !== encoded
+ ) {
+ throw new InvalidShareUrlError('Invalid v2 share framing');
+ }
+ const contentRootDepth = (bytes[1] << 8) | bytes[2];
+ if (contentRootDepth < 1) throw new InvalidShareUrlError('Invalid content root depth');
+ const urlBytes = bytes.subarray(V2_HEADER_BYTES);
+ if (urlBytes.length > MAX_V2_SHARED_URL_UTF8_BYTES) {
+ throw new InvalidShareUrlError('Share URL exceeds the v2 limit');
+ }
+ let sharedUrl: string;
+ try {
+ sharedUrl = new TextDecoder('utf-8', { fatal: true }).decode(urlBytes);
+ } catch {
+ throw new InvalidShareUrlError('Share payload body is not valid UTF-8');
+ }
+ const source = parseCanonicalGitHubShareUrl(sharedUrl);
+ if (contentRootDepth > source.targetSegments.length) {
+ throw new InvalidShareUrlError('Content root depth exceeds the target');
+ }
+ const targetPath = source.targetSegments.slice(contentRootDepth).join('/');
+ if (source.kind === 'doc' && targetPath === '') {
+ throw new InvalidShareUrlError('Document target cannot be the content root');
+ }
+ return { version: 2, sharedUrl, contentRootDepth, source, targetPath };
+}
+
+function parseCanonicalGitHubShareUrl(sharedUrl: string): CanonicalGitHubShareSource {
+ if (!sharedUrl.startsWith('https://') || sharedUrl.includes('?') || sharedUrl.includes('#')) {
+ throw new InvalidShareUrlError('Share URL is not canonical HTTPS');
+ }
+ const authorityAndPath = sharedUrl.slice('https://'.length);
+ const pathStart = authorityAndPath.indexOf('/');
+ if (pathStart <= 0) throw new InvalidShareUrlError('Share URL is missing a repository path');
+ const host = authorityAndPath.slice(0, pathStart);
+ const hostLabels = host.split('.');
+ if (
+ host.length > 253 ||
+ host !== host.toLowerCase() ||
+ host.endsWith('.') ||
+ host.includes(':') ||
+ IPV4_AUTHORITY_PATTERN.test(host) ||
+ hostLabels.some(
+ (label) =>
+ label.length === 0 || label.length > 63 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),
+ ) ||
+ classifyGitHubShareHost(host) !== host
+ ) {
+ throw new InvalidShareUrlError('Share URL host is not canonical');
+ }
+ const rawSegments = authorityAndPath.slice(pathStart + 1).split('/');
+ if (rawSegments.length < 4 || rawSegments.some((segment) => segment === '')) {
+ throw new InvalidShareUrlError('Share URL path is invalid');
+ }
+ const [rawOwner, rawRepo, rawKind, rawBranch, ...rawTarget] = rawSegments;
+ if (rawKind !== 'blob' && rawKind !== 'tree') {
+ throw new InvalidShareUrlError('Share URL kind is invalid');
+ }
+ const owner = decodeCanonicalComponent(rawOwner);
+ const repo = decodeCanonicalComponent(rawRepo);
+ const branch = decodeCanonicalComponent(rawBranch);
+ const targetSegments = rawTarget.map(decodeCanonicalComponent);
+ if (!isShareSegmentSafe(owner, repo, branch)) {
+ throw new InvalidShareUrlError('Share URL repository identity is invalid');
+ }
+ for (const component of [owner, repo, ...targetSegments]) assertCanonicalPathComponent(component);
+ const kind = rawKind === 'blob' ? 'doc' : 'folder';
+ if (kind === 'doc' && targetSegments.length === 0) {
+ throw new InvalidShareUrlError('Document URL is missing its target');
+ }
+ const source = {
+ host,
+ owner,
+ repo,
+ branch,
+ kind,
+ targetSegments,
+ } satisfies CanonicalGitHubShareSource;
+ if (serializeCanonicalGitHubShareUrl(source) !== sharedUrl) {
+ throw new InvalidShareUrlError('Share URL is not canonically serialized');
+ }
+ return source;
+}
+
+function decodeCanonicalComponent(raw: string): string {
+ let decoded: string;
+ try {
+ decoded = decodeURIComponent(raw);
+ } catch {
+ throw new InvalidShareUrlError('Malformed percent encoding');
+ }
+ if (encodeURIComponent(decoded) !== raw) {
+ throw new InvalidShareUrlError('Non-canonical percent encoding');
+ }
+ return decoded;
+}
+
+function assertCanonicalPathComponent(component: string): void {
+ if (
+ component === '' ||
+ component === '.' ||
+ component === '..' ||
+ component.toLowerCase() === '.git' ||
+ component.includes('/') ||
+ component.includes('\\') ||
+ [...component].some((char) => char.charCodeAt(0) <= 0x1f || char.charCodeAt(0) === 0x7f)
+ ) {
+ throw new InvalidShareUrlError('Invalid path component');
+ }
+}
+
+function serializeCanonicalGitHubShareUrl(source: CanonicalGitHubShareSource): string {
+ const kind = source.kind === 'doc' ? 'blob' : 'tree';
+ return `https://${source.host}/${[
+ source.owner,
+ source.repo,
+ kind,
+ source.branch,
+ ...source.targetSegments,
+ ]
+ .map(encodeURIComponent)
+ .join('/')}`;
+}
+
+function peekBase64UrlVersion(input: string): number | null {
+ if (input.length < 2) return null;
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
+ const first = alphabet.indexOf(input[0]);
+ const second = alphabet.indexOf(input[1]);
+ if (first < 0 || second < 0) return null;
+ return (first << 2) | (second >>> 4);
+}
+
+function uint8ArrayToBase64Url(bytes: Uint8Array): string {
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function base64UrlToUint8Array(input: string): Uint8Array {
@@ -315,13 +494,13 @@ export { DOWNLOAD_URL as SPLASH_DOWNLOAD_URL } from './site';
/**
* Build the custom-scheme handoff URL the splash's "Open in OpenKnowledge"
- * button fires. Custom-scheme path carries the shared URL (a blob URL for a
- * doc, a tree URL for a folder) directly without the version byte — that path
- * is the immediate-handoff channel, not the marketing-safe persisted-link
- * channel.
+ * button fires. V1 keeps its historical direct `url` parameter; v2 carries
+ * the canonical token unchanged so content-root depth survives the handoff.
*/
-export function buildCustomSchemeUrl(sharedUrl: string): string {
- return `openknowledge://share?url=${encodeURIComponent(sharedUrl)}`;
+export function buildCustomSchemeUrl(sharedUrl: string, token?: string): string {
+ return token === undefined
+ ? `openknowledge://share?url=${encodeURIComponent(sharedUrl)}`
+ : `openknowledge://share?token=${token}`;
}
/**
@@ -470,10 +649,33 @@ export function buildSplashViewModel(encoded: string): SplashView {
if (err instanceof UnsupportedShareVersionError) {
return { kind: 'unsupported-version', version: err.version };
}
+ if (!(err instanceof InvalidShareUrlError)) {
+ // An unexpected throw (not the expected malformed-token rejection) means
+ // this copy-local decoder diverged from the core codec it mirrors, or hit
+ // an injected-dep bug. Surface it (server-side → Vercel logs) so a
+ // regression is diagnosable instead of collapsing into the generic
+ // "invalid link" every recipient sees. Expected InvalidShareUrlError stays
+ // quiet so bots hitting /d/<garbage> don't flood the logs.
+ console.warn(
+ `[share-splash] unexpected share-decode error (errorKind: ${
+ err instanceof Error ? err.name : typeof err
+ })`,
+ );
+ }
return { kind: 'invalid' };
}
- const parsed = parseGitHubShareUrl(decoded.sharedUrl);
+ const parsed =
+ decoded.version === 2
+ ? {
+ kind: decoded.source.kind,
+ host: decoded.source.host,
+ owner: decoded.source.owner,
+ repo: decoded.source.repo,
+ branch: decoded.source.branch,
+ path: decoded.targetPath,
+ }
+ : parseGitHubShareUrl(decoded.sharedUrl);
if (!parsed) {
return { kind: 'invalid' };
}
@@ -497,7 +699,10 @@ export function buildSplashViewModel(encoded: string): SplashView {
branch,
isDefaultBranch: isCommonDefaultBranch(branch),
sharedUrl: decoded.sharedUrl,
- customSchemeUrl: buildCustomSchemeUrl(decoded.sharedUrl),
+ customSchemeUrl: buildCustomSchemeUrl(
+ decoded.sharedUrl,
+ decoded.version === 2 ? encoded : undefined,
+ ),
githubUrl: decoded.sharedUrl,
};
}
diff --git a/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
index 8f983bfa4..8ce439417 100644
--- a/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
+++ b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
@@ -93,6 +93,13 @@ function makeCrashBridge(): CrashBridgeStub {
};
}
+function installCrashBridge(stub: CrashBridgeStub): (() => void) | undefined {
+ // Test setup can install the module singleton before this file runs. Detach
+ // its bridge first so the first test gets the same isolation as later tests.
+ crashInviteStore.install({ bridge: stub.bridge })?.();
+ return crashInviteStore.install({ bridge: stub.bridge });
+}
+
describe('ReportBugCrashInviteTrigger', () => {
let uninstall: (() => void) | undefined;
@@ -106,7 +113,7 @@ describe('ReportBugCrashInviteTrigger', () => {
test('a crash-detected push opens the crash-invite dialog', async () => {
const stub = makeCrashBridge();
- uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ uninstall = installCrashBridge(stub);
render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
expect(screen.queryByRole('dialog')).toBeNull();
@@ -123,7 +130,7 @@ describe('ReportBugCrashInviteTrigger', () => {
test('an invitation delivered before the component mounts is buffered, not dropped', async () => {
const stub = makeCrashBridge();
- uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ uninstall = installCrashBridge(stub);
stub.fire(INVITE);
render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
@@ -142,7 +149,7 @@ describe('ReportBugCrashInviteTrigger', () => {
// place would carry the first crash's mount-time state onto the second and
// ship one crash's account stamped with the other's id.
const stub = makeCrashBridge();
- uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ uninstall = installCrashBridge(stub);
render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
stub.fire(INVITE);
@@ -182,7 +189,7 @@ describe('ReportBugCrashInviteTrigger', () => {
test('Not now acks the crash event and closes the invitation', async () => {
const stub = makeCrashBridge();
- uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ uninstall = installCrashBridge(stub);
render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
stub.fire(INVITE);
await waitFor(
@@ -205,7 +212,7 @@ describe('ReportBugCrashInviteTrigger', () => {
test('dismissing via Escape also counts as the answer and acks', async () => {
const stub = makeCrashBridge();
- uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ uninstall = installCrashBridge(stub);
render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
stub.fire(INVITE);
await waitFor(
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
index 3e7affb8d..34831e445 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
@@ -168,10 +168,12 @@ function projectBranchSwitchPayload(): Extract<
return {
kind: 'project-branch-switch',
share: {
+ contentRootDepth: null,
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'feat/branch-x',
sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/feat/branch-x/docs/notes.md',
+ repositoryTarget: { kind: 'doc', docPath: 'docs/notes.md' },
target: { kind: 'doc', docPath: 'docs/notes.md' },
},
projectPath: '/Users/alice/projects/open-knowledge',
@@ -200,10 +202,12 @@ describe('ShareBranchSwitchDialog — payload gating', () => {
cb({
kind: 'launcher-miss',
share: {
+ contentRootDepth: null,
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/x.md',
+ repositoryTarget: { kind: 'doc', docPath: 'docs/x.md' },
target: { kind: 'doc', docPath: 'docs/x.md' },
},
});
@@ -308,7 +312,11 @@ describe('ShareBranchSwitchDialog — Open-in-current dispatch', () => {
const firstArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;
expect(firstArg).toBeDefined();
expect(firstArg.path).toBe(payload.projectPath);
- expect(firstArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });
+ expect(firstArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/notes.md',
+ repositoryPath: 'docs/notes.md',
+ });
// Stay-on-current: no share-branch threading.
expect(firstArg.pendingBranch).toBeUndefined();
// Store dismissed after dispatch.
@@ -435,7 +443,11 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
});
const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;
expect(openArg).toBeDefined();
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/notes.md',
+ repositoryPath: 'docs/notes.md',
+ });
expect(openArg.pendingBranch).toBe(payload.share.branch);
});
@@ -674,7 +686,11 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
expect(calls.open).toHaveBeenCalledTimes(1);
});
const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/notes.md',
+ repositoryPath: 'docs/notes.md',
+ });
expect(openArg.pendingBranch).toBe(payload.share.branch);
});
@@ -705,7 +721,11 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
});
const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;
// Navigation lands on the renamed path, NOT the original share path.
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'guides/notes.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'guides/notes.md',
+ repositoryPath: 'guides/notes.md',
+ });
});
test('deleted verdict hands off to the miss dialog (no switch, dismisses this shell)', async () => {
@@ -721,6 +741,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
expect(missDialogStore.getSnapshot()).toEqual({
kind: 'doc',
path: 'docs/notes.md',
+ repositoryPath: 'docs/notes.md',
branch: 'feat/branch-x',
});
});
@@ -1021,7 +1042,11 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const base = projectBranchSwitchPayload();
const payload = {
...base,
- share: { ...base.share, target: { kind: 'folder' as const, folderPath: 'docs' } },
+ share: {
+ ...base.share,
+ repositoryTarget: { kind: 'folder' as const, folderPath: 'docs' },
+ target: { kind: 'folder' as const, folderPath: 'docs' },
+ },
};
const { bridge, calls } = makeBridge();
renderDialog(bridge, store, payload);
@@ -1036,7 +1061,11 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
expect(calls.open).toHaveBeenCalledTimes(1);
});
const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'folder', path: 'docs' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'folder',
+ path: 'docs',
+ repositoryPath: 'docs',
+ });
expect(openArg.pendingBranch).toBe(payload.share.branch);
});
@@ -1079,7 +1108,11 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
path: worktreePath,
target: 'new-window',
entryPoint: 'worktree',
- pendingDeepLinkTarget: { kind: 'doc', path: 'docs/notes.md' },
+ pendingDeepLinkTarget: {
+ kind: 'doc',
+ path: 'docs/notes.md',
+ repositoryPath: 'docs/notes.md',
+ },
pendingBranch: payload.share.branch,
});
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsx
index e0fec881f..547511e65 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx
@@ -80,6 +80,29 @@ type ProjectBranchSwitchPayload = Extract<
{ kind: 'project-branch-switch' }
>;
+function shareRepositoryPath(share: ProjectBranchSwitchPayload['share']): string {
+ return shareTargetPath(share.repositoryTarget);
+}
+
+function pendingTarget(
+ share: ProjectBranchSwitchPayload['share'],
+ path = shareTargetPath(share.target),
+) {
+ const repositoryPath =
+ share.contentRootDepth === null
+ ? path
+ : [
+ ...shareRepositoryPath(share).split('/').slice(0, share.contentRootDepth),
+ ...(path === '' ? [] : path.split('/')),
+ ].join('/');
+ return {
+ kind: share.target.kind,
+ path,
+ repositoryPath,
+ ...(share.contentRootDepth === null ? {} : { contentRootDepth: share.contentRootDepth }),
+ };
+}
+
function isBranchSwitchPayload(
payload: OkShareReceivedPayload | null,
): payload is ProjectBranchSwitchPayload {
@@ -140,8 +163,8 @@ export function ShareBranchSwitchDialog({
.fetchBranchInfo({
projectPath: active.projectPath,
branch: active.share.branch,
- kind: active.share.target.kind,
- path: shareTargetPath(active.share.target),
+ kind: active.share.repositoryTarget.kind,
+ path: shareRepositoryPath(active.share),
})
.then((info) => {
if (cancelled) return;
@@ -183,7 +206,10 @@ export function ShareBranchSwitchDialog({
projectPath: active.projectPath,
branch: active.share.branch,
kind: active.share.target.kind,
- path: shareTargetPath(active.share.target),
+ path: shareRepositoryPath(active.share),
+ ...(active.share.contentRootDepth === null
+ ? {}
+ : { contentRootDepth: active.share.contentRootDepth }),
})
.then((status) => {
if (verdictPayloadRef.current !== fetchedFor) return;
@@ -215,6 +241,10 @@ export function ShareBranchSwitchDialog({
missDialogStore.arm({
kind: active.share.target.kind,
path: shareTargetPath(active.share.target),
+ repositoryPath: shareRepositoryPath(active.share),
+ ...(active.share.contentRootDepth === null
+ ? {}
+ : { contentRootDepth: active.share.contentRootDepth }),
branch: active.share.branch,
});
store.dismiss();
@@ -270,10 +300,7 @@ export function ShareBranchSwitchDialog({
path: active.projectPath,
target: 'new-window',
entryPoint: 'share-receive',
- pendingDeepLinkTarget: {
- kind: active.share.target.kind,
- path: pendingNavPath,
- },
+ pendingDeepLinkTarget: pendingTarget(active.share, pendingNavPath),
pendingBranch: shareBranch,
})
.catch((err) => {
@@ -419,7 +446,7 @@ export function ShareBranchSwitchDialog({
path: projectPath,
target: 'new-window',
entryPoint: 'share-receive',
- pendingDeepLinkTarget: { kind: share.target.kind, path: shareTargetPath(share.target) },
+ pendingDeepLinkTarget: pendingTarget(share),
})
.catch((err) => {
console.warn(
@@ -549,10 +576,7 @@ export function ShareBranchSwitchDialog({
path: target,
target: 'new-window',
entryPoint: 'worktree',
- pendingDeepLinkTarget: {
- kind: share.target.kind,
- path: shareTargetPath(share.target),
- },
+ pendingDeepLinkTarget: pendingTarget(share),
pendingBranch: shareBranch,
})
.catch((err) => {
@@ -607,7 +631,7 @@ export function ShareBranchSwitchDialog({
path: target,
target: 'new-window',
entryPoint: 'share-receive',
- pendingDeepLinkTarget: { kind: share.target.kind, path: shareTargetPath(share.target) },
+ pendingDeepLinkTarget: pendingTarget(share),
pendingBranch: shareBranch,
})
.catch((err) => {
diff --git a/packages/app/src/components/ShareReceiveDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
index df374f455..e204120b3 100644
--- a/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
@@ -33,11 +33,13 @@ function okPayload(
return {
kind: 'launcher-miss',
share: {
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md',
+ repositoryTarget: { kind: 'doc', docPath: 'docs/guide.md' },
target: { kind: 'doc', docPath: 'docs/guide.md' },
...overrides,
},
@@ -433,7 +435,11 @@ describe('ShareReceiveDialog runtime behavior', () => {
expect(bridge.project.open).toHaveBeenCalledWith({
entryPoint: 'share-receive',
path: '/cloned/open-knowledge',
- pendingDeepLinkTarget: { kind: 'doc', path: 'docs/guide.md' },
+ pendingDeepLinkTarget: {
+ kind: 'doc',
+ path: 'docs/guide.md',
+ repositoryPath: 'docs/guide.md',
+ },
target: 'new-window',
}),
);
@@ -539,7 +545,11 @@ describe('ShareReceiveDialog runtime behavior', () => {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/guide.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/guide.md',
+ repositoryPath: 'docs/guide.md',
+ });
expect(openArg.pendingShareBranchSwitch).toBeUndefined();
// Guard the success path: a dropped store.dismiss() would leave a ghost
// dialog over the newly opened project window.
@@ -606,7 +616,11 @@ describe('ShareReceiveDialog runtime behavior', () => {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/guide.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/guide.md',
+ repositoryPath: 'docs/guide.md',
+ });
expect(openArg.pendingShareBranchSwitch).toBeUndefined();
expect(store.dismiss).toHaveBeenCalled();
});
@@ -631,7 +645,11 @@ describe('ShareReceiveDialog runtime behavior', () => {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/guide.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/guide.md',
+ repositoryPath: 'docs/guide.md',
+ });
expect(openArg.pendingShareBranchSwitch).toBeUndefined();
expect(store.dismiss).toHaveBeenCalled();
});
@@ -659,7 +677,11 @@ describe('ShareReceiveDialog runtime behavior', () => {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
- expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/guide.md' });
+ expect(openArg.pendingDeepLinkTarget).toEqual({
+ kind: 'doc',
+ path: 'docs/guide.md',
+ repositoryPath: 'docs/guide.md',
+ });
expect(openArg.pendingShareBranchSwitch).toBeUndefined();
expect(store.dismiss).toHaveBeenCalled();
});
diff --git a/packages/app/src/components/ShareReceiveDialog.tsx b/packages/app/src/components/ShareReceiveDialog.tsx
index a71e0d242..9330ac057 100644
--- a/packages/app/src/components/ShareReceiveDialog.tsx
+++ b/packages/app/src/components/ShareReceiveDialog.tsx
@@ -98,6 +98,15 @@ export interface ShareReceiveDialogProps {
type LauncherConsentPayload = Extract<OkShareReceivedPayload, { kind: 'launcher-consent' }>;
type LauncherMissPayload = Extract<OkShareReceivedPayload, { kind: 'launcher-miss' }>;
+function pendingTarget(share: LauncherMissPayload['share'] | LauncherConsentPayload['share']) {
+ return {
+ kind: share.target.kind,
+ path: shareTargetPath(share.target),
+ repositoryPath: shareTargetPath(share.repositoryTarget),
+ ...(share.contentRootDepth === null ? {} : { contentRootDepth: share.contentRootDepth }),
+ };
+}
+
function isLauncherConsentPayload(
payload: OkShareReceivedPayload | null,
): payload is LauncherConsentPayload {
@@ -219,6 +228,10 @@ function ShareReceiveDialogInner({
branch: payload.share.branch,
targetPath: shareTargetPath(payload.share.target),
targetKind: payload.share.target.kind,
+ repositoryPath: shareTargetPath(payload.share.repositoryTarget),
+ ...(payload.share.contentRootDepth === null
+ ? {}
+ : { contentRootDepth: payload.share.contentRootDepth }),
parentProjectName: payload.parentProjectName,
}),
);
@@ -310,10 +323,7 @@ function ShareReceiveDialogInner({
path: result.dir,
target: 'new-window',
entryPoint: 'share-receive',
- pendingDeepLinkTarget: {
- kind: launcherMiss.share.target.kind,
- path: shareTargetPath(launcherMiss.share.target),
- },
+ pendingDeepLinkTarget: pendingTarget(launcherMiss.share),
});
// Dismiss only on a successful open — mirrors handleLocalCtaClick. If
// the open fails the clone already succeeded, so keep the dialog mounted
@@ -408,10 +418,7 @@ function ShareReceiveDialogInner({
},
}
: {
- pendingDeepLinkTarget: {
- kind: launcherMiss.share.target.kind,
- path: shareTargetPath(launcherMiss.share.target),
- },
+ pendingDeepLinkTarget: pendingTarget(launcherMiss.share),
}),
});
store.dismiss();
@@ -456,7 +463,14 @@ function ShareReceiveDialogInner({
path: outcome.projectPath,
target: 'new-window',
entryPoint: 'share-receive',
- pendingDeepLinkTarget: { kind: seed.targetKind, path: seed.targetPath },
+ pendingDeepLinkTarget: {
+ kind: seed.targetKind,
+ path: seed.targetPath,
+ repositoryPath: seed.repositoryPath ?? seed.targetPath,
+ ...(seed.contentRootDepth === undefined
+ ? {}
+ : { contentRootDepth: seed.contentRootDepth }),
+ },
pendingBranch: seed.branch,
});
setConsentState((prev) =>
diff --git a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
index 0e861e9e4..4329f2c5b 100644
--- a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
@@ -346,6 +346,7 @@ describe('ShareReceiveMissDialog', () => {
expect(pendingReceiveNavStore.getSnapshot()).toEqual({
kind: 'doc',
path: 'knowledge/new-plan.md',
+ repositoryPath: 'knowledge/new-plan.md',
branch: 'feature',
});
await waitFor(() => {
@@ -465,6 +466,7 @@ describe('ShareReceiveMissDialog pull recovery', () => {
expect(pendingReceiveNavStore.getSnapshot()).toEqual({
kind: 'doc',
path: 'notes/plan.md',
+ repositoryPath: 'notes/plan.md',
branch: 'feature',
});
});
@@ -484,6 +486,7 @@ describe('ShareReceiveMissDialog pull recovery', () => {
expect(pendingReceiveNavStore.getSnapshot()).toEqual({
kind: 'folder',
path: 'docs/guides',
+ repositoryPath: 'docs/guides',
branch: 'feature',
});
});
diff --git a/packages/app/src/components/ShareReceiveMissDialog.tsx b/packages/app/src/components/ShareReceiveMissDialog.tsx
index 1d1b109f4..9b05b8abf 100644
--- a/packages/app/src/components/ShareReceiveMissDialog.tsx
+++ b/packages/app/src/components/ShareReceiveMissDialog.tsx
@@ -28,6 +28,7 @@ import { hashFromDocName, hashFromFolderPath } from '@/lib/doc-hash';
import { missDialogStore } from '@/lib/share/miss-dialog-store';
import {
type PendingReceiveNav,
+ pendingReceiveNavForContentPath,
pendingReceiveNavStore,
} from '@/lib/share/pending-receive-nav-store';
@@ -68,7 +69,7 @@ function ShareReceiveMissDialogInner({ nav }: { nav: PendingReceiveNav }) {
* instead of the create-mode editor.
*/
function navigateWithBackstop(path: string): void {
- pendingReceiveNavStore.arm({ kind: nav.kind, path, branch: nav.branch });
+ pendingReceiveNavStore.arm(pendingReceiveNavForContentPath(nav, path));
window.location.hash = nav.kind === 'folder' ? hashFromFolderPath(path) : hashFromDocName(path);
dismiss();
}
diff --git a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
index e7dec9418..2e6487edf 100644
--- a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
@@ -154,6 +154,7 @@ describe('ShareReceiveMissPanel verdict surfaces', () => {
expect(pendingReceiveNavStore.getSnapshot()).toEqual({
kind: 'doc',
path: 'knowledge/new-plan',
+ repositoryPath: 'knowledge/new-plan',
branch: 'feature',
});
});
diff --git a/packages/app/src/components/ShareReceiveMissPanel.tsx b/packages/app/src/components/ShareReceiveMissPanel.tsx
index e1479e901..ab2301724 100644
--- a/packages/app/src/components/ShareReceiveMissPanel.tsx
+++ b/packages/app/src/components/ShareReceiveMissPanel.tsx
@@ -7,6 +7,7 @@ import {
import { hashFromDocName, hashFromFolderPath } from '@/lib/doc-hash';
import {
type PendingReceiveNav,
+ pendingReceiveNavForContentPath,
pendingReceiveNavStore,
} from '@/lib/share/pending-receive-nav-store';
@@ -22,7 +23,6 @@ import {
export function ShareReceiveMissPanel({ nav }: { nav: PendingReceiveNav }) {
const { state, refetch } = useShareTargetVerdict(nav);
const containerRef = useRef<HTMLDivElement>(null);
- const branch = nav.branch;
// Focus the primary action (the first button — the rename redirect where
// present, else Browse folder) once a verdict resolves, so keyboard users land
@@ -39,7 +39,7 @@ export function ShareReceiveMissPanel({ nav }: { nav: PendingReceiveNav }) {
// Re-arm for the redirect target so, if the rename destination is also
// missing locally (the receiver's ref is behind), the miss surface renders
// for it too instead of the create-mode editor.
- pendingReceiveNavStore.arm({ kind: nav.kind, path: renamedTo, branch });
+ pendingReceiveNavStore.arm(pendingReceiveNavForContentPath(nav, renamedTo));
window.location.hash =
nav.kind === 'folder' ? hashFromFolderPath(renamedTo) : hashFromDocName(renamedTo);
}
diff --git a/packages/app/src/components/share-receive-miss-content.tsx b/packages/app/src/components/share-receive-miss-content.tsx
index 0f1e00c9b..1e774fa09 100644
--- a/packages/app/src/components/share-receive-miss-content.tsx
+++ b/packages/app/src/components/share-receive-miss-content.tsx
@@ -79,8 +79,9 @@ export function useShareTargetVerdict(nav: PendingReceiveNav): {
.fetchTargetStatus({
projectPath: bridge.config.projectPath,
branch,
- path: nav.path,
+ path: nav.repositoryPath ?? nav.path,
kind: nav.kind,
+ ...(nav.contentRootDepth === undefined ? {} : { contentRootDepth: nav.contentRootDepth }),
})
.then((response) => {
// `null` is a transport failure; the proxy already coerces a skewed 200
@@ -102,7 +103,7 @@ export function useShareTargetVerdict(nav: PendingReceiveNav): {
return () => {
cancelled = true;
};
- }, [branch, nav.kind, nav.path, epoch]);
+ }, [branch, nav.kind, nav.path, nav.repositoryPath, nav.contentRootDepth, epoch]);
return {
state,
refetch: () => {
diff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.ts
index abb728363..a7e03e388 100644
--- a/packages/app/src/lib/install-deep-link-listener.test.ts
+++ b/packages/app/src/lib/install-deep-link-listener.test.ts
@@ -234,6 +234,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
expect(pendingReceiveNavStore.getSnapshot()).toEqual({
kind: 'doc',
path: normalizeTargetPath('notes/plan').normalizedTarget,
+ repositoryPath: 'notes/plan',
branch: 'feature',
});
});
@@ -267,6 +268,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
expect(missDialogStore.getSnapshot()).toEqual({
kind: 'doc',
path: 'notes/plan',
+ repositoryPath: 'notes/plan',
branch: 'feature',
});
expect(pendingReceiveNavStore.getSnapshot()).toBeNull();
@@ -281,6 +283,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
expect(missDialogStore.getSnapshot()).toEqual({
kind: 'folder',
path: 'docs/sub',
+ repositoryPath: 'docs/sub',
branch: null,
});
expect(pendingReceiveNavStore.getSnapshot()).toBeNull();
diff --git a/packages/app/src/lib/install-deep-link-listener.ts b/packages/app/src/lib/install-deep-link-listener.ts
index d5d7631f0..facd4ab8d 100644
--- a/packages/app/src/lib/install-deep-link-listener.ts
+++ b/packages/app/src/lib/install-deep-link-listener.ts
@@ -116,7 +116,13 @@ export function installDeepLinkListener(
const kind = evt.kind ?? 'doc';
// Keep the share target's file extension: the verdict fetch needs the real
// repo path, and both stores normalize for matching.
- const nav = { kind, path: evt.doc, branch: evt.branch ?? null };
+ const nav = {
+ kind,
+ path: evt.doc,
+ repositoryPath: evt.repositoryPath ?? evt.doc,
+ ...(evt.contentRootDepth === undefined ? {} : { contentRootDepth: evt.contentRootDepth }),
+ branch: evt.branch ?? null,
+ };
// Main's pre-nav stat probe already found the target absent on the
// receiver's checked-out branch (deleted / renamed / not yet fetched). Show
// the honest verdict as a modal WITHOUT navigating to the dead path — no
diff --git a/packages/app/src/lib/share/consent-flow.ts b/packages/app/src/lib/share/consent-flow.ts
index 359319099..71e54941d 100644
--- a/packages/app/src/lib/share/consent-flow.ts
+++ b/packages/app/src/lib/share/consent-flow.ts
@@ -35,6 +35,8 @@ export interface ConsentFlowSeed {
readonly branch: string;
/** Share's target path (doc or folder) — threaded to bridge.open as pendingDeepLinkTarget.path. */
readonly targetPath: string;
+ readonly repositoryPath?: string;
+ readonly contentRootDepth?: number;
/** Share's target kind — threaded to bridge.open as pendingDeepLinkTarget.kind. */
readonly targetKind: 'doc' | 'folder';
/**
diff --git a/packages/app/src/lib/share/pending-receive-nav-store.test.ts b/packages/app/src/lib/share/pending-receive-nav-store.test.ts
index 36be73b55..161fa7572 100644
--- a/packages/app/src/lib/share/pending-receive-nav-store.test.ts
+++ b/packages/app/src/lib/share/pending-receive-nav-store.test.ts
@@ -6,6 +6,7 @@ import {
matchesShareReceiveMiss,
type PendingReceiveNav,
type PendingReceiveNavStore,
+ pendingReceiveNavForContentPath,
} from './pending-receive-nav-store';
const DOC_NAV: PendingReceiveNav = { kind: 'doc', path: 'notes/plan', branch: 'feature' };
@@ -49,6 +50,23 @@ describe('matchesShareReceiveMiss', () => {
});
});
+describe('pendingReceiveNavForContentPath', () => {
+ test('keeps a v2 content-root folder repository path canonical', () => {
+ expect(
+ pendingReceiveNavForContentPath(
+ {
+ kind: 'folder',
+ path: 'guides',
+ repositoryPath: 'wiki/guides',
+ contentRootDepth: 1,
+ branch: 'main',
+ },
+ '',
+ ),
+ ).toMatchObject({ path: '', repositoryPath: 'wiki' });
+ });
+});
+
describe('hashSelectsPendingNav', () => {
test('a doc hash still selects the armed doc (branch query ignored)', () => {
expect(hashSelectsPendingNav('#/notes/plan?branch=feature', DOC_NAV)).toBe(true);
diff --git a/packages/app/src/lib/share/pending-receive-nav-store.ts b/packages/app/src/lib/share/pending-receive-nav-store.ts
index cfa4bd200..659582702 100644
--- a/packages/app/src/lib/share/pending-receive-nav-store.ts
+++ b/packages/app/src/lib/share/pending-receive-nav-store.ts
@@ -33,6 +33,10 @@ export interface PendingReceiveNav {
* extension-stripped `activeTarget.target`.
*/
readonly path: string;
+ /** Repository-relative coordinate used only for filesystem and git probes. */
+ readonly repositoryPath?: string;
+ /** Number of repository-path segments hidden from v2 renderer navigation. */
+ readonly contentRootDepth?: number;
/** Share branch the target-status verdict fetch keys off; null on legacy branch-less shares. */
readonly branch: string | null;
}
@@ -129,6 +133,22 @@ export function createPendingReceiveNavStore(): PendingReceiveNavStore {
/** Module-level singleton — the deep-link listener arms it, EditorArea reads it. */
export const pendingReceiveNavStore: PendingReceiveNavStore = createPendingReceiveNavStore();
+export function pendingReceiveNavForContentPath(
+ nav: PendingReceiveNav,
+ path: string,
+): PendingReceiveNav {
+ if (nav.contentRootDepth === undefined) {
+ return { ...nav, path, repositoryPath: path };
+ }
+ const repositoryPath = nav.repositoryPath ?? nav.path;
+ const prefix = repositoryPath.split('/').slice(0, nav.contentRootDepth);
+ return {
+ ...nav,
+ path,
+ repositoryPath: [...prefix, ...(path === '' ? [] : path.split('/'))].join('/'),
+ };
+}
+
/**
* The pending share-receive nav the editor should render as an honest miss
* panel instead of create-mode, or null when the active target isn't a
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index c23e2363d..7adc50dee 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -291,7 +291,15 @@ export interface OkProjectOpenRequest {
* `sendDeepLink` for the warm-focus path. Mirrors the existing
* `openknowledge://open?project=&doc=` flow.
*/
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ /** Content-relative renderer navigation path. */
+ path: string;
+ /** Repository-relative path used only by receive-side Git/filesystem probes. */
+ repositoryPath?: string;
+ /** Present only for v2; strips the repository prefix from rename results. */
+ contentRootDepth?: number;
+ };
/**
* Optional share branch riding alongside `pendingDeepLinkTarget`. See
* canonical bridge contract below.
@@ -416,6 +424,10 @@ export interface OkSharePayloadFields {
readonly repo: string;
readonly branch: string;
readonly sharedUrl: string;
+ /** URL-derived repository coordinate. Never inferred from receiver config. */
+ readonly repositoryTarget: ShareTarget;
+ /** `null` for historical v1; positive decoded prefix depth for v2. */
+ readonly contentRootDepth: number | null;
readonly target: ShareTarget;
}
@@ -1310,6 +1322,8 @@ export interface OkDesktopBridge {
branch?: string | null;
multiCandidate?: boolean;
targetMissing?: boolean;
+ repositoryPath?: string;
+ contentRootDepth?: number;
}) => void,
): OkUnsubscribe;
/**
@@ -1610,6 +1624,7 @@ export interface OkDesktopBridge {
projectPath: string;
branch: string;
kind: 'doc' | 'folder';
+ /** URL-derived repository-relative target path. */
path: string;
}): Promise<BranchInfoResponse | null>;
/**
@@ -1630,8 +1645,11 @@ export interface OkDesktopBridge {
fetchTargetStatus(request: {
projectPath: string;
branch: string;
+ /** URL-derived repository-relative target path. */
path: string;
kind: 'doc' | 'folder';
+ /** Present only for v2 so rename destinations can be content-relative. */
+ contentRootDepth?: number;
}): Promise<ShareTargetStatusResponse | null>;
/**
* Gate dialog dismissal on the `branch-switched` broadcast landing
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 158491b22..79c9a4cee 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1746,9 +1746,12 @@ export {
type CandidateBridgeDeps,
type CandidateSelection,
type CandidateSelectionPayload,
+ type CanonicalGitHubShareSource,
canonicalGitHubRemoteUrl,
classifyBranchMatch,
type DecodedShare,
+ type DecodedShareV1,
+ type DecodedShareV2,
decodeShareUrl,
type ExpectedShareRepo,
encodeShareUrl,
@@ -1756,9 +1759,15 @@ export {
type HeadBranchInfo,
InvalidShareUrlError,
isGitWorkingTree,
+ MAX_V2_SHARE_PAYLOAD_BYTES,
+ MAX_V2_SHARE_TOKEN_CHARS,
+ MAX_V2_SHARED_URL_UTF8_BYTES,
+ parseCanonicalGitHubShareUrl,
+ projectCanonicalGitHubShareTarget,
type RecentProjectEntry,
type ResolvedGitDirKind,
selectCandidate,
+ serializeCanonicalGitHubShareUrl,
UnsupportedShareVersionError,
} from './sharing/index.ts';
export {
diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.ts
index 45dcd7d72..cc830e5eb 100644
--- a/packages/core/src/schemas/api/share.ts
+++ b/packages/core/src/schemas/api/share.ts
@@ -747,15 +747,17 @@ export type ShareTargetStatusVerdict = z.infer<typeof ShareTargetStatusVerdictSc
/**
* Request body for `POST /api/share/target-status`. `branch` is the share
* link's target branch (validated via the shared seven-rule predicate);
- * `path` is the content-relative target path (empty string = content-root
- * folder share); `kind` disambiguates doc vs folder for the removal-commit
- * lookup.
+ * `path` is the URL-derived repository-relative target path. V2 additionally
+ * carries its positive `contentRootDepth` so a verified rename destination can
+ * be projected back to the renderer's content-relative coordinate. V1 omits
+ * the depth and keeps repository-relative rename results unchanged.
*/
export const ShareTargetStatusRequestSchema = z
.object({
branch: refineBranchName(z.string().min(1)),
path: z.string(),
kind: z.enum(['doc', 'folder']),
+ contentRootDepth: z.number().int().min(1).max(0xffff).optional(),
})
.loose() satisfies StandardSchemaV1;
export type ShareTargetStatusRequest = z.infer<typeof ShareTargetStatusRequestSchema>;
diff --git a/packages/core/src/sharing/index.ts b/packages/core/src/sharing/index.ts
index 0a50bc5f4..340b77eb8 100644
--- a/packages/core/src/sharing/index.ts
+++ b/packages/core/src/sharing/index.ts
@@ -17,9 +17,18 @@ export {
type ResolvedGitDirKind,
} from './receive-flow.ts';
export {
+ type CanonicalGitHubShareSource,
type DecodedShare,
+ type DecodedShareV1,
+ type DecodedShareV2,
decodeShareUrl,
encodeShareUrl,
InvalidShareUrlError,
+ MAX_V2_SHARE_PAYLOAD_BYTES,
+ MAX_V2_SHARE_TOKEN_CHARS,
+ MAX_V2_SHARED_URL_UTF8_BYTES,
+ parseCanonicalGitHubShareUrl,
+ projectCanonicalGitHubShareTarget,
+ serializeCanonicalGitHubShareUrl,
UnsupportedShareVersionError,
} from './share-url.ts';
diff --git a/packages/core/src/sharing/share-url-v2.test.ts b/packages/core/src/sharing/share-url-v2.test.ts
new file mode 100644
index 000000000..62135e997
--- /dev/null
+++ b/packages/core/src/sharing/share-url-v2.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, test } from 'vitest';
+
+import corpus from '../../../../test-support/fixtures/share-url-v1-v2.json' with { type: 'json' };
+import {
+ frozenV1CustomSchemeOutcome,
+ frozenV1DecodeShareToken,
+} from '../../../../test-support/share/frozen-v1-share-reader.test-helper.ts';
+import {
+ decodeShareUrl,
+ encodeShareUrl,
+ InvalidShareUrlError,
+ UnsupportedShareVersionError,
+} from './share-url.ts';
+
+const v1Shares = corpus.validShares.filter((fixture) => fixture.version === 1);
+const v2Shares = corpus.validShares.filter((fixture) => fixture.version === 2);
+
+describe('fixed cross-version corpus', () => {
+ test('pins the exact protocol bounds and literal maximum token', () => {
+ const { bounds } = corpus;
+ expect(bounds.maxCase.token).toHaveLength(bounds.maxV2TokenChars);
+ expect(new TextEncoder().encode(bounds.maxCase.sharedUrl)).toHaveLength(
+ bounds.maxV2SharedUrlUtf8Bytes,
+ );
+ expect(
+ new TextEncoder().encode(`openknowledge://share?token=${bounds.maxCase.token}`),
+ ).toHaveLength(bounds.maxV2CustomUriChars);
+ expect(bounds.overLimitToken).toHaveLength(bounds.maxV2TokenChars + 1);
+ });
+
+ test.each(v1Shares)('$id stays byte-compatible with the frozen v1 reader', (fixture) => {
+ expect(frozenV1DecodeShareToken(fixture.token)).toEqual({
+ kind: 'ok',
+ version: 1,
+ sharedUrl: fixture.sharedUrl,
+ });
+ expect(decodeShareUrl(fixture.token)).toEqual({
+ version: 1,
+ sharedUrl: fixture.sharedUrl,
+ });
+ expect(encodeShareUrl(fixture.sharedUrl)).toBe(fixture.token);
+ });
+
+ test.each(corpus.legacyAliases)('$id retains historical v1 tolerance', (fixture) => {
+ expect(frozenV1DecodeShareToken(fixture.token)).toEqual({
+ kind: 'ok',
+ version: 1,
+ sharedUrl: fixture.sharedUrl,
+ });
+ expect(decodeShareUrl(fixture.token)).toEqual({
+ version: 1,
+ sharedUrl: fixture.sharedUrl,
+ });
+ });
+
+ test.each(v2Shares)('$id is unsupported to the frozen v1 universal reader', (fixture) => {
+ expect(frozenV1DecodeShareToken(fixture.token)).toEqual({
+ kind: 'unsupported-version',
+ version: 2,
+ });
+ });
+
+ test.each(
+ corpus.customSchemeCases.map((fixture) => [fixture.id, fixture.uri, fixture.baseline] as const),
+ )('%s has the pinned frozen custom-scheme outcome', (_id, uri, expected) => {
+ expect(frozenV1CustomSchemeOutcome(uri)).toBe(expected);
+ });
+});
+
+describe('v2 codec and content projection', () => {
+ test.each(
+ v2Shares,
+ )('$id decodes its repository source and content-relative target', (fixture) => {
+ expect(decodeShareUrl(fixture.token)).toEqual(
+ expect.objectContaining({
+ version: 2,
+ contentRootDepth: fixture.contentRootDepth,
+ sharedUrl: fixture.sharedUrl,
+ target: fixture.target,
+ }),
+ );
+ });
+
+ test.each(v2Shares)('$id encodes to the fixed literal token', (fixture) => {
+ expect(encodeShareUrl(fixture.sharedUrl, fixture.contentRootDepth)).toBe(fixture.token);
+ });
+
+ test('depth zero continues to select the exact historical v1 representation', () => {
+ const fixture = v1Shares[0];
+ expect(encodeShareUrl(fixture.sharedUrl, 0)).toBe(fixture.token);
+ });
+
+ test('accepts the exact maximum v2 payload and projects its document target', () => {
+ expect(decodeShareUrl(corpus.bounds.maxCase.token)).toEqual(
+ expect.objectContaining({
+ version: 2,
+ contentRootDepth: 1,
+ sharedUrl: corpus.bounds.maxCase.sharedUrl,
+ target: corpus.bounds.maxCase.target,
+ }),
+ );
+ expect(encodeShareUrl(corpus.bounds.maxCase.sharedUrl, 1)).toBe(corpus.bounds.maxCase.token);
+ });
+
+ // Asserting the exact error, not just the class, is what pins the size gate
+ // to the front of the pipeline. An over-limit token stays invalid either way,
+ // so a bare class assertion still passes with the gate deleted: the token
+ // falls through and fails later as `Share payload is not valid base64url`.
+ // Only the message distinguishes rejected-on-sight from rejected-after-work,
+ // which is the bounded-decoding property the gate exists to hold.
+ test('rejects input one character over the v2 token bound before decoding it', () => {
+ expect(() => decodeShareUrl(corpus.bounds.overLimitToken)).toThrow(
+ new InvalidShareUrlError('Share token exceeds the v2 size limit'),
+ );
+ });
+
+ test('retains unbounded historical v1 decoding beyond the v2 token ceiling', () => {
+ const sharedUrl = `https://github.com/o/r/blob/main/${'a'.repeat(4000)}.md`;
+ const token = encodeShareUrl(sharedUrl);
+ expect(token.length).toBeGreaterThan(corpus.bounds.maxV2TokenChars);
+ expect(decodeShareUrl(token)).toEqual({ version: 1, sharedUrl });
+ });
+
+ test('rejects obviously oversized v2 input before URL parsing', () => {
+ expect(() => encodeShareUrl('x'.repeat(2986), 1)).toThrow(
+ new InvalidShareUrlError('Share URL exceeds the v2 URL size limit'),
+ );
+ });
+});
+
+describe('v2 trust-boundary classification', () => {
+ test.each(corpus.invalidTokens)('$id is invalid rather than unsupported', (fixture) => {
+ expect(() => decodeShareUrl(fixture.token)).toThrow(InvalidShareUrlError);
+ });
+
+ test.each(
+ corpus.invalidTokens.filter(
+ (
+ fixture,
+ ): fixture is typeof fixture & {
+ readonly sharedUrl: string;
+ readonly contentRootDepth: number;
+ } => fixture.sharedUrl !== undefined && fixture.contentRootDepth !== undefined,
+ ),
+ )('$id cannot be minted as a second spelling', (fixture) => {
+ expect(() => encodeShareUrl(fixture.sharedUrl, fixture.contentRootDepth)).toThrow(
+ InvalidShareUrlError,
+ );
+ });
+
+ test.each(corpus.unsupportedTokens)('$id remains an unsupported future version', (fixture) => {
+ let caught: unknown;
+ try {
+ decodeShareUrl(fixture.token);
+ } catch (error) {
+ caught = error;
+ }
+ expect(caught).toBeInstanceOf(UnsupportedShareVersionError);
+ expect((caught as UnsupportedShareVersionError).version).toBe(fixture.version);
+ });
+
+ test('rejects a noncanonical base64url alias even when it decodes to valid v2 bytes', () => {
+ const fixture = corpus.invalidTokens.find(
+ (candidate) => candidate.id === 'v2-noncanonical-base64-alias',
+ );
+ expect(fixture).toBeDefined();
+ expect(() => decodeShareUrl(fixture?.token ?? '')).toThrow(InvalidShareUrlError);
+ });
+
+ test('rejects encoded traversal before WHATWG URL normalization can erase it', () => {
+ const fixture = corpus.invalidTokens.find(
+ (candidate) => candidate.id === 'v2-target-encoded-dotdot',
+ );
+ expect(fixture).toBeDefined();
+ expect(() => decodeShareUrl(fixture?.token ?? '')).toThrow(InvalidShareUrlError);
+ });
+});
diff --git a/packages/core/src/sharing/share-url.test.ts b/packages/core/src/sharing/share-url.test.ts
index 2d4a3e65d..2516da4d8 100644
--- a/packages/core/src/sharing/share-url.test.ts
+++ b/packages/core/src/sharing/share-url.test.ts
@@ -1,10 +1,5 @@
import { describe, expect, test } from 'vitest';
-import {
- decodeShareUrl,
- encodeShareUrl,
- InvalidShareUrlError,
- UnsupportedShareVersionError,
-} from './share-url.ts';
+import { decodeShareUrl, encodeShareUrl, InvalidShareUrlError } from './share-url.ts';
describe('encodeShareUrl', () => {
test('returns a base64url string with no padding for a simple blob URL', () => {
@@ -43,22 +38,15 @@ describe('decodeShareUrl', () => {
expect(decodeShareUrl(encodeShareUrl(sharedUrl))).toEqual({ version: 1, sharedUrl });
});
- test('throws UnsupportedShareVersionError when the version byte is not 0x01', () => {
- // Build a v2-shaped payload directly: [0x02] + utf-8 bytes of a URL.
+ test('throws InvalidShareUrlError for a recognized v2 payload with malformed framing', () => {
+ // Build a malformed v2 payload without its required depth header.
const blobBytes = new TextEncoder().encode('https://example.com/foo');
const bytes = new Uint8Array(1 + blobBytes.length);
bytes[0] = 0x02;
bytes.set(blobBytes, 1);
const encoded = uint8ArrayToBase64UrlForTest(bytes);
- let caught: unknown;
- try {
- decodeShareUrl(encoded);
- } catch (e) {
- caught = e;
- }
- expect(caught).toBeInstanceOf(UnsupportedShareVersionError);
- expect((caught as UnsupportedShareVersionError).version).toBe(2);
+ expect(() => decodeShareUrl(encoded)).toThrow(InvalidShareUrlError);
});
test('throws InvalidShareUrlError on undecodable base64url input', () => {
diff --git a/packages/core/src/sharing/share-url.ts b/packages/core/src/sharing/share-url.ts
index b2cee2f61..469b5c578 100644
--- a/packages/core/src/sharing/share-url.ts
+++ b/packages/core/src/sharing/share-url.ts
@@ -1,32 +1,44 @@
-/**
- * Share URL codec for the `https://openknowledge.ai/d/<base64url>` link form.
- *
- * Payload shape (by contract, 1-way once shipped):
- * v1 = [0x01] || utf-8 bytes of the github blob URL
- *
- * Future versions reuse the same `/d/` path prefix by bumping the leading
- * byte; substrate changes (cloud-native shares, project-level shares) get
- * new path prefixes (`/s/`, `/p/`).
- *
- * Core is browser+Node compatible — no `node:` imports, no `Buffer`. Uses
- * `TextEncoder`/`TextDecoder` and `btoa`/`atob` which exist in both runtimes
- * (Node 16+, every modern browser, Bun).
- */
+import { classifyGitHubShareHost } from '../constants/github.ts';
+import type { ShareTarget } from '../desktop-bridge.ts';
+import { isValidBranchName } from '../schemas/api/share.ts';
const SHARE_URL_VERSION_V1 = 0x01;
+const SHARE_URL_VERSION_V2 = 0x02;
+const V2_HEADER_BYTES = 3;
+const SHARE_OWNER_REPO_PATTERN = /^[A-Za-z0-9._-]+$/;
+const IPV4_AUTHORITY_PATTERN = /^(?:\d{1,3}\.){3}\d{1,3}$/;
-export interface DecodedShare {
- version: number;
- sharedUrl: string;
+export const MAX_V2_SHARE_TOKEN_CHARS = 3984;
+export const MAX_V2_SHARE_PAYLOAD_BYTES = 2988;
+export const MAX_V2_SHARED_URL_UTF8_BYTES = 2985;
+
+export interface DecodedShareV1 {
+ readonly version: 1;
+ readonly sharedUrl: string;
+}
+
+export interface CanonicalGitHubShareSource {
+ readonly host: string;
+ readonly owner: string;
+ readonly repo: string;
+ readonly branch: string;
+ readonly kind: 'doc' | 'folder';
+ readonly targetSegments: readonly string[];
}
-/**
- * Thrown when `decodeShareUrl` finds a version byte the current build does
- * not understand. Carries the observed numeric byte so the UI layer can
- * render a meaningful "Update OpenKnowledge" toast.
- */
+export interface DecodedShareV2 {
+ readonly version: 2;
+ readonly sharedUrl: string;
+ readonly contentRootDepth: number;
+ readonly source: CanonicalGitHubShareSource;
+ readonly target: ShareTarget;
+}
+
+export type DecodedShare = DecodedShareV1 | DecodedShareV2;
+
export class UnsupportedShareVersionError extends Error {
readonly version: number;
+
constructor(version: number) {
super(`Unsupported share URL version: 0x${version.toString(16).padStart(2, '0')}`);
this.name = 'UnsupportedShareVersionError';
@@ -34,10 +46,6 @@ export class UnsupportedShareVersionError extends Error {
}
}
-/**
- * Thrown when the payload is not a well-formed v1 share URL — undecodable
- * base64url, empty, or non-UTF-8 body bytes.
- */
export class InvalidShareUrlError extends Error {
constructor(message: string) {
super(message);
@@ -45,42 +53,55 @@ export class InvalidShareUrlError extends Error {
}
}
-/**
- * Encode a GitHub blob URL into the v1 base64url share payload.
- *
- * encodeShareUrl('https://github.com/a/b/blob/main/c.md')
- * // → 'AWh0dHBzOi8vZ2l0aHViLmNvbS9hL2IvYmxvYi9tYWluL2MubWQ'
- */
-export function encodeShareUrl(sharedUrl: string): string {
- const blobBytes = new TextEncoder().encode(sharedUrl);
- const bytes = new Uint8Array(1 + blobBytes.length);
- bytes[0] = SHARE_URL_VERSION_V1;
- bytes.set(blobBytes, 1);
- return uint8ArrayToBase64Url(bytes);
+export function encodeShareUrl(sharedUrl: string, contentRootDepth = 0): string {
+ assertContentRootDepth(contentRootDepth, true);
+ if (contentRootDepth === 0) {
+ return encodeV1ShareUrl(sharedUrl);
+ }
+ if (sharedUrl.length > MAX_V2_SHARED_URL_UTF8_BYTES) {
+ throw new InvalidShareUrlError('Share URL exceeds the v2 URL size limit');
+ }
+
+ const source = parseCanonicalGitHubShareUrl(sharedUrl);
+ projectCanonicalGitHubShareTarget(source, contentRootDepth);
+
+ const sharedUrlBytes = new TextEncoder().encode(sharedUrl);
+ if (sharedUrlBytes.length > MAX_V2_SHARED_URL_UTF8_BYTES) {
+ throw new InvalidShareUrlError('Share URL exceeds the v2 URL size limit');
+ }
+
+ const bytes = new Uint8Array(V2_HEADER_BYTES + sharedUrlBytes.length);
+ bytes[0] = SHARE_URL_VERSION_V2;
+ bytes[1] = contentRootDepth >>> 8;
+ bytes[2] = contentRootDepth & 0xff;
+ bytes.set(sharedUrlBytes, V2_HEADER_BYTES);
+
+ if (bytes.length > MAX_V2_SHARE_PAYLOAD_BYTES) {
+ throw new InvalidShareUrlError('Share payload exceeds the v2 size limit');
+ }
+
+ const encoded = uint8ArrayToBase64Url(bytes);
+ if (encoded.length > MAX_V2_SHARE_TOKEN_CHARS) {
+ throw new InvalidShareUrlError('Share token exceeds the v2 size limit');
+ }
+ return encoded;
}
-/**
- * Decode a base64url payload back into its `{ version, sharedUrl }`. Tolerates
- * an appended `?query` and/or `#fragment` (extensibility by contract) by
- * trimming them before base64url-decoding the body.
- *
- * Throws `UnsupportedShareVersionError` when the leading byte is not 0x01;
- * throws `InvalidShareUrlError` for empty, malformed base64url, or non-UTF-8
- * bodies.
- */
export function decodeShareUrl(encoded: string): DecodedShare {
- const cleaned = encoded.split(/[?#]/)[0];
- if (cleaned.length === 0) {
- throw new InvalidShareUrlError('Share payload is empty');
+ const peekedVersion = peekBase64UrlVersion(encoded);
+
+ if (peekedVersion === SHARE_URL_VERSION_V2 && encoded.length > MAX_V2_SHARE_TOKEN_CHARS) {
+ throw new InvalidShareUrlError('Share token exceeds the v2 size limit');
}
- let bytes: Uint8Array;
- try {
- bytes = base64UrlToUint8Array(cleaned);
- } catch {
- throw new InvalidShareUrlError('Share payload is not valid base64url');
+ const suffixIndex = encoded.search(/[?#]/);
+ if (peekedVersion === SHARE_URL_VERSION_V2) {
+ if (suffixIndex !== -1) throw new InvalidShareUrlError('V2 share tokens cannot have a suffix');
+ return decodeV2ShareUrl(encoded);
}
+ const cleaned = suffixIndex === -1 ? encoded : encoded.slice(0, suffixIndex);
+ const bytes = decodeBase64Url(cleaned);
if (bytes.length === 0) {
throw new InvalidShareUrlError('Share payload is empty');
}
@@ -90,33 +111,300 @@ export function decodeShareUrl(encoded: string): DecodedShare {
throw new UnsupportedShareVersionError(version);
}
- // `fatal: true` makes TextDecoder throw on invalid UTF-8 instead of
- // silently substituting U+FFFD — the contract here is "round-trips back to
- // the exact same string or signals InvalidShareUrlError."
- const decoder = new TextDecoder('utf-8', { fatal: true });
- let sharedUrl: string;
+ return {
+ version: 1,
+ sharedUrl: decodeUtf8(bytes.subarray(1)),
+ };
+}
+
+export function parseCanonicalGitHubShareUrl(sharedUrl: string): CanonicalGitHubShareSource {
+ if (!sharedUrl.startsWith('https://')) {
+ throw new InvalidShareUrlError('Share URL must use canonical HTTPS spelling');
+ }
+ if (sharedUrl.includes('?') || sharedUrl.includes('#')) {
+ throw new InvalidShareUrlError('Share URL cannot contain a query or fragment');
+ }
+
+ const authorityAndPath = sharedUrl.slice('https://'.length);
+ const pathStart = authorityAndPath.indexOf('/');
+ if (pathStart <= 0) {
+ throw new InvalidShareUrlError('Share URL is missing its repository path');
+ }
+
+ const host = authorityAndPath.slice(0, pathStart);
+ assertCanonicalGitHubHost(host);
+
+ const rawPath = authorityAndPath.slice(pathStart + 1);
+ const rawSegments = rawPath.split('/');
+ if (rawSegments.length < 4 || rawSegments.some((segment) => segment.length === 0)) {
+ throw new InvalidShareUrlError('Share URL has an invalid path shape');
+ }
+
+ const [rawOwner, rawRepo, rawKind, rawBranch, ...rawTargetSegments] = rawSegments;
+ if (rawKind !== 'blob' && rawKind !== 'tree') {
+ throw new InvalidShareUrlError('Share URL has an unsupported repository path shape');
+ }
+
+ const owner = decodeCanonicalRepositoryComponent(rawOwner, 'owner');
+ const repo = decodeCanonicalRepositoryComponent(rawRepo, 'repository');
+ const branch = decodeCanonicalBranch(rawBranch);
+ const targetSegments = rawTargetSegments.map((segment) =>
+ decodeCanonicalPathComponent(segment, 'target'),
+ );
+ const kind = rawKind === 'blob' ? 'doc' : 'folder';
+
+ if (kind === 'doc' && targetSegments.length === 0) {
+ throw new InvalidShareUrlError('Document share URL is missing its target path');
+ }
+
+ const source: CanonicalGitHubShareSource = {
+ host,
+ owner,
+ repo,
+ branch,
+ kind,
+ targetSegments,
+ };
+ if (serializeCanonicalGitHubShareUrl(source) !== sharedUrl) {
+ throw new InvalidShareUrlError('Share URL is not canonically serialized');
+ }
+ return source;
+}
+
+export function serializeCanonicalGitHubShareUrl(source: CanonicalGitHubShareSource): string {
+ assertCanonicalGitHubHost(source.host);
+ assertDecodedRepositoryComponent(source.owner, 'owner');
+ assertDecodedRepositoryComponent(source.repo, 'repository');
+ if (!isValidBranchName(source.branch)) {
+ throw new InvalidShareUrlError('Share URL branch is invalid');
+ }
+ if (source.kind !== 'doc' && source.kind !== 'folder') {
+ throw new InvalidShareUrlError('Share URL target kind is invalid');
+ }
+ if (source.kind === 'doc' && source.targetSegments.length === 0) {
+ throw new InvalidShareUrlError('Document share URL is missing its target path');
+ }
+ for (const segment of source.targetSegments) {
+ assertDecodedPathComponent(segment, 'target');
+ }
+
+ const kind = source.kind === 'doc' ? 'blob' : 'tree';
+ const structuralSegments = [
+ encodeURIComponent(source.owner),
+ encodeURIComponent(source.repo),
+ kind,
+ encodeURIComponent(source.branch),
+ ...source.targetSegments.map((segment) => encodeURIComponent(segment)),
+ ];
+ return `https://${source.host}/${structuralSegments.join('/')}`;
+}
+
+export function projectCanonicalGitHubShareTarget(
+ source: CanonicalGitHubShareSource,
+ contentRootDepth: number,
+): ShareTarget {
+ assertContentRootDepth(contentRootDepth, false);
+ if (contentRootDepth > source.targetSegments.length) {
+ throw new InvalidShareUrlError('Content root depth exceeds the repository target path');
+ }
+
+ const contentPath = source.targetSegments.slice(contentRootDepth).join('/');
+ if (source.kind === 'doc') {
+ if (contentPath.length === 0) {
+ throw new InvalidShareUrlError('Document share target cannot be the content root');
+ }
+ return { kind: 'doc', docPath: contentPath };
+ }
+ return { kind: 'folder', folderPath: contentPath };
+}
+
+function encodeV1ShareUrl(sharedUrl: string): string {
+ const sharedUrlBytes = new TextEncoder().encode(sharedUrl);
+ const bytes = new Uint8Array(1 + sharedUrlBytes.length);
+ bytes[0] = SHARE_URL_VERSION_V1;
+ bytes.set(sharedUrlBytes, 1);
+ return uint8ArrayToBase64Url(bytes);
+}
+
+function decodeV2ShareUrl(encoded: string): DecodedShareV2 {
+ const bytes = decodeBase64Url(encoded);
+ if (bytes.length > MAX_V2_SHARE_PAYLOAD_BYTES) {
+ throw new InvalidShareUrlError('Share payload exceeds the v2 size limit');
+ }
+ if (uint8ArrayToBase64Url(bytes) !== encoded) {
+ throw new InvalidShareUrlError('V2 share token is not canonically encoded');
+ }
+ if (bytes.length <= V2_HEADER_BYTES) {
+ throw new InvalidShareUrlError('V2 share payload is truncated');
+ }
+
+ const contentRootDepth = (bytes[1] << 8) | bytes[2];
+ assertContentRootDepth(contentRootDepth, false);
+
+ const sharedUrlBytes = bytes.subarray(V2_HEADER_BYTES);
+ if (sharedUrlBytes.length > MAX_V2_SHARED_URL_UTF8_BYTES) {
+ throw new InvalidShareUrlError('Share URL exceeds the v2 URL size limit');
+ }
+ const sharedUrl = decodeUtf8(sharedUrlBytes);
+ const source = parseCanonicalGitHubShareUrl(sharedUrl);
+ const target = projectCanonicalGitHubShareTarget(source, contentRootDepth);
+ return {
+ version: 2,
+ sharedUrl,
+ contentRootDepth,
+ source,
+ target,
+ };
+}
+
+function assertContentRootDepth(contentRootDepth: number, allowZero: boolean): void {
+ if (
+ !Number.isInteger(contentRootDepth) ||
+ contentRootDepth < (allowZero ? 0 : 1) ||
+ contentRootDepth > 0xffff
+ ) {
+ throw new InvalidShareUrlError('Content root depth is invalid');
+ }
+}
+
+function assertCanonicalGitHubHost(host: string): void {
+ if (
+ host.length === 0 ||
+ host.length > 253 ||
+ host.endsWith('.') ||
+ host !== host.toLowerCase() ||
+ IPV4_AUTHORITY_PATTERN.test(host)
+ ) {
+ throw new InvalidShareUrlError('Share URL host is not canonical');
+ }
+ const labels = host.split('.');
+ if (
+ labels.some(
+ (label) =>
+ label.length === 0 || label.length > 63 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),
+ )
+ ) {
+ throw new InvalidShareUrlError('Share URL host is not a DNS name');
+ }
+ if (classifyGitHubShareHost(host) !== host) {
+ throw new InvalidShareUrlError('Share URL host is not a canonical GitHub host');
+ }
+}
+
+function decodeCanonicalBranch(rawBranch: string): string {
+ const branch = decodeCanonicalComponent(rawBranch, 'branch');
+ if (!isValidBranchName(branch)) {
+ throw new InvalidShareUrlError('Share URL branch is invalid');
+ }
+ return branch;
+}
+
+function decodeCanonicalPathComponent(
+ rawComponent: string,
+ role: 'owner' | 'repository' | 'target',
+): string {
+ const component = decodeCanonicalComponent(rawComponent, role);
+ assertDecodedPathComponent(component, role);
+ return component;
+}
+
+function decodeCanonicalRepositoryComponent(
+ rawComponent: string,
+ role: 'owner' | 'repository',
+): string {
+ const component = decodeCanonicalComponent(rawComponent, role);
+ assertDecodedRepositoryComponent(component, role);
+ return component;
+}
+
+function decodeCanonicalComponent(rawComponent: string, role: string): string {
+ let component: string;
try {
- sharedUrl = decoder.decode(bytes.subarray(1));
+ component = decodeURIComponent(rawComponent);
+ } catch {
+ throw new InvalidShareUrlError(`Share URL ${role} has malformed percent encoding`);
+ }
+ if (encodeURIComponent(component) !== rawComponent) {
+ throw new InvalidShareUrlError(`Share URL ${role} is not canonically encoded`);
+ }
+ return component;
+}
+
+function assertDecodedPathComponent(component: string, role: string): void {
+ if (
+ component.length === 0 ||
+ component === '.' ||
+ component === '..' ||
+ component.toLowerCase() === '.git' ||
+ component.includes('/') ||
+ component.includes('\\') ||
+ containsControlOrDel(component)
+ ) {
+ throw new InvalidShareUrlError(`Share URL ${role} component is invalid`);
+ }
+}
+
+function assertDecodedRepositoryComponent(component: string, role: 'owner' | 'repository'): void {
+ assertDecodedPathComponent(component, role);
+ if (!SHARE_OWNER_REPO_PATTERN.test(component) || component.startsWith('-')) {
+ throw new InvalidShareUrlError(`Share URL ${role} component is invalid`);
+ }
+}
+
+function containsControlOrDel(value: string): boolean {
+ for (let index = 0; index < value.length; index++) {
+ const codeUnit = value.charCodeAt(index);
+ if (codeUnit <= 0x1f || codeUnit === 0x7f) return true;
+ }
+ return false;
+}
+
+function decodeUtf8(bytes: Uint8Array): string {
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch {
throw new InvalidShareUrlError('Share payload body is not valid UTF-8');
}
+}
+
+function decodeBase64Url(input: string): Uint8Array {
+ if (input.length === 0) {
+ throw new InvalidShareUrlError('Share payload is empty');
+ }
+ try {
+ return base64UrlToUint8Array(input);
+ } catch {
+ throw new InvalidShareUrlError('Share payload is not valid base64url');
+ }
+}
+
+function peekBase64UrlVersion(input: string): number | null {
+ if (input.length < 2) return null;
+ const first = base64UrlAlphabetIndex(input.charCodeAt(0));
+ const second = base64UrlAlphabetIndex(input.charCodeAt(1));
+ if (first === -1 || second === -1) return null;
+ return (first << 2) | (second >>> 4);
+}
- return { version, sharedUrl };
+function base64UrlAlphabetIndex(codeUnit: number): number {
+ if (codeUnit >= 65 && codeUnit <= 90) return codeUnit - 65;
+ if (codeUnit >= 97 && codeUnit <= 122) return codeUnit - 97 + 26;
+ if (codeUnit >= 48 && codeUnit <= 57) return codeUnit - 48 + 52;
+ if (codeUnit === 45) return 62;
+ if (codeUnit === 95) return 63;
+ return -1;
}
function uint8ArrayToBase64Url(bytes: Uint8Array): string {
let binaryString = '';
- for (let i = 0; i < bytes.length; i++) {
- binaryString += String.fromCharCode(bytes[i]);
+ for (let index = 0; index < bytes.length; index++) {
+ binaryString += String.fromCharCode(bytes[index]);
}
const base64 = btoa(binaryString);
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function base64UrlToUint8Array(input: string): Uint8Array {
- // Reject any character outside the base64url alphabet up-front; `atob` is
- // surprisingly lenient on some platforms (e.g. it silently ignores some
- // non-alphabet bytes) and we want a deterministic InvalidShareUrlError.
if (!/^[A-Za-z0-9_-]*$/.test(input)) {
throw new Error('Input contains non-base64url characters');
}
@@ -124,8 +412,8 @@ function base64UrlToUint8Array(input: string): Uint8Array {
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
const binaryString = atob(padded);
const bytes = new Uint8Array(binaryString.length);
- for (let i = 0; i < binaryString.length; i++) {
- bytes[i] = binaryString.charCodeAt(i);
+ for (let index = 0; index < binaryString.length; index++) {
+ bytes[index] = binaryString.charCodeAt(index);
}
return bytes;
}
diff --git a/packages/desktop/src/main/branch-info-proxy.ts b/packages/desktop/src/main/branch-info-proxy.ts
index bb5634ec9..ae100771f 100644
--- a/packages/desktop/src/main/branch-info-proxy.ts
+++ b/packages/desktop/src/main/branch-info-proxy.ts
@@ -340,7 +340,13 @@ export async function proxyRunCheckout(
* would abort the request before the server's fail-open answer arrives.
*/
export async function proxyShareTargetStatus(
- request: { projectPath: string; branch: string; path: string; kind: 'doc' | 'folder' },
+ request: {
+ projectPath: string;
+ branch: string;
+ path: string;
+ kind: 'doc' | 'folder';
+ contentRootDepth?: number;
+ },
deps: BranchInfoProxyDeps,
signal?: AbortSignal,
): Promise<ShareTargetStatusResponse | null> {
@@ -358,6 +364,9 @@ export async function proxyShareTargetStatus(
branch: request.branch,
path: request.path,
kind: request.kind,
+ ...(request.contentRootDepth === undefined
+ ? {}
+ : { contentRootDepth: request.contentRootDepth }),
}),
signal: composeFetchSignal(timeoutMs, signal),
});
diff --git a/packages/desktop/src/main/check-target-exists.test.ts b/packages/desktop/src/main/check-target-exists.test.ts
index 4d507aeeb..4f3ae0444 100644
--- a/packages/desktop/src/main/check-target-exists.test.ts
+++ b/packages/desktop/src/main/check-target-exists.test.ts
@@ -7,6 +7,8 @@ import {
checkProjectDirExists,
checkTargetExists,
computeShareTargetMissing,
+ resolveShareProbeRoot,
+ resolveTargetProbeCoordinate,
} from './check-target-exists.ts';
describe('checkTargetExists', () => {
@@ -390,6 +392,58 @@ describe('computeShareTargetMissing', () => {
});
});
+describe('resolveShareProbeRoot', () => {
+ test('maps a nested content.dir to the local content coordinate', () => {
+ expect(resolveShareProbeRoot('/project', () => 'wiki')).toBe('/project/wiki');
+ });
+
+ test('keeps the project root for dot, load failures, and escaping values', () => {
+ expect(resolveShareProbeRoot('/project', () => '.')).toBe('/project');
+ expect(
+ resolveShareProbeRoot('/project', () => {
+ throw new Error('invalid config');
+ }),
+ ).toBe('/project');
+ expect(resolveShareProbeRoot('/project', () => '../outside')).toBe('/project');
+ });
+
+ test('emits a bounded errorKind diagnostic when config resolution throws', () => {
+ const warnings: Array<{ obj: object; msg: string }> = [];
+ const root = resolveShareProbeRoot(
+ '/project',
+ () => {
+ throw new TypeError('config parse failed');
+ },
+ { warn: (obj, msg) => warnings.push({ obj, msg }) },
+ );
+ expect(root).toBe('/project');
+ expect(warnings).toEqual([
+ {
+ obj: { errorKind: 'TypeError' },
+ msg: '[receive] content.dir resolution failed — probing the project root',
+ },
+ ]);
+ });
+});
+
+describe('resolveTargetProbeCoordinate', () => {
+ test('keeps ordinary deep links content-relative under a nested content root', () => {
+ expect(
+ resolveTargetProbeCoordinate('/project', { kind: 'folder', path: 'wiki' }, () => 'wiki'),
+ ).toEqual({ root: '/project/wiki', target: { kind: 'folder', path: 'wiki' } });
+ });
+
+ test('uses the explicit repository coordinate without reapplying content.dir', () => {
+ expect(
+ resolveTargetProbeCoordinate(
+ '/project',
+ { kind: 'folder', path: '', repositoryPath: 'wiki' },
+ () => 'wiki',
+ ),
+ ).toEqual({ root: '/project', target: { kind: 'folder', path: 'wiki' } });
+ });
+});
+
describe('checkProjectDirExists', () => {
function makeTmp(): string {
return mkdtempSync(join(tmpdir(), 'ok-check-project-dir-'));
diff --git a/packages/desktop/src/main/check-target-exists.ts b/packages/desktop/src/main/check-target-exists.ts
index 245cfb562..c2398de81 100644
--- a/packages/desktop/src/main/check-target-exists.ts
+++ b/packages/desktop/src/main/check-target-exists.ts
@@ -234,3 +234,51 @@ export function computeShareTargetMissing(
if (target.kind === 'folder' && target.path === '') return false;
return probe(projectPath, target.kind, target.path) === 'missing';
}
+
+/** Optional structured logger for the pre-server probe's graceful-fail paths. */
+type ShareProbeLogger = { warn(obj: object, msg: string): void };
+
+/**
+ * Resolve the filesystem root for a content-relative share target before the
+ * local pre-server probe. Config loading is deliberately injected so the helper
+ * stays deterministic; any read/parse failure falls back to the historical
+ * project root rather than blocking the receive flow. The fallback emits a
+ * bounded `errorKind` diagnostic (when a logger is wired) so a silent probe of
+ * the wrong root — which can render a false "not on this branch yet" panel —
+ * stays observable instead of vanishing.
+ */
+export function resolveShareProbeRoot(
+ projectPath: string,
+ readContentDir: (projectPath: string) => string,
+ log?: ShareProbeLogger,
+): string {
+ if (!isSafeProjectPath(projectPath)) return projectPath;
+ try {
+ const candidate = resolve(projectPath, readContentDir(projectPath));
+ const projectWithSep = projectPath.endsWith(sep) ? projectPath : projectPath + sep;
+ return candidate === projectPath || candidate.startsWith(projectWithSep)
+ ? candidate
+ : projectPath;
+ } catch (err) {
+ log?.warn(
+ { errorKind: err instanceof Error ? err.name : typeof err },
+ '[receive] content.dir resolution failed — probing the project root',
+ );
+ return projectPath;
+ }
+}
+
+export function resolveTargetProbeCoordinate(
+ projectPath: string,
+ target: { kind: 'doc' | 'folder'; path: string; repositoryPath?: string },
+ readContentDir: (projectPath: string) => string,
+ log?: ShareProbeLogger,
+): { root: string; target: { kind: 'doc' | 'folder'; path: string } } {
+ if (target.repositoryPath !== undefined) {
+ return { root: projectPath, target: { kind: target.kind, path: target.repositoryPath } };
+ }
+ return {
+ root: resolveShareProbeRoot(projectPath, readContentDir, log),
+ target: { kind: target.kind, path: target.path },
+ };
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 23a8155ce..2d747c04b 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -55,6 +55,7 @@ import {
getOkArtifactPaths,
isEntryUpToDate,
isOwnManagedEntry,
+ loadConfig,
type McpInstallOptions,
okBugReportsDir,
type ProjectAiIntegrationsResult,
@@ -207,6 +208,7 @@ import {
checkProjectDirExists,
checkTargetExists as checkTargetExistsImpl,
computeShareTargetMissing,
+ resolveTargetProbeCoordinate,
} from './check-target-exists.ts';
import {
cliProbeArgs,
@@ -2171,7 +2173,12 @@ const BOOT_BUDGET_FILE_CAP = 10_000;
async function openProject(
projectPath: string,
entryPoint: EntryPoint,
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string },
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ },
pendingBranch?: string | null,
pendingMultiCandidate?: boolean,
pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload,
@@ -2671,7 +2678,12 @@ function pruneRecentIfMissing(projectPath: string): { removed: boolean; name: st
async function openProjectOrFallbackToNavigator(
projectPath: string,
entryPoint: EntryPoint,
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string },
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ },
pendingBranch?: string | null,
pendingMultiCandidate?: boolean,
pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload,
@@ -6089,9 +6101,21 @@ function registerIpcHandlers() {
// moved/deleted target flags `targetMissing` and the editor renders the
// honest verdict panel instead of the create-mode editor. Synchronous native
// probe — no new IPC — computed once for both the warm and cold branches.
- const targetMissing =
- request.pendingDeepLinkTarget !== undefined &&
- computeShareTargetMissing(checkTargetExistsImpl, request.path, request.pendingDeepLinkTarget);
+ const targetMissing = (() => {
+ const target = request.pendingDeepLinkTarget;
+ if (target === undefined) return false;
+ const probeCoordinate = resolveTargetProbeCoordinate(
+ request.path,
+ target,
+ (projectPath) => loadConfig(projectPath).config.content.dir,
+ getLogger('share-receive'),
+ );
+ return computeShareTargetMissing(
+ checkTargetExistsImpl,
+ probeCoordinate.root,
+ probeCoordinate.target,
+ );
+ })();
// Warm-focus path for share-receive: when an existing window holds the
// requested project, focus it and dispatch the deep-link directly. Mirrors
// the URL-scheme warm path in url-scheme.ts so the IPC and the deep-link
@@ -6106,6 +6130,12 @@ function registerIpcHandlers() {
kind: request.pendingDeepLinkTarget.kind,
branch: request.pendingBranch ?? null,
multiCandidate: request.pendingMultiCandidate === true,
+ ...(request.pendingDeepLinkTarget.repositoryPath === undefined
+ ? {}
+ : { repositoryPath: request.pendingDeepLinkTarget.repositoryPath }),
+ ...(request.pendingDeepLinkTarget.contentRootDepth === undefined
+ ? {}
+ : { contentRootDepth: request.pendingDeepLinkTarget.contentRootDepth }),
// Only carry the flag when set — keeps the common (present) case's
// payload identical to the pre-gate shape.
...(targetMissing ? { targetMissing: true } : {}),
@@ -8109,6 +8139,7 @@ function bootPrimaryInstance(): void {
// arrived somewhere, so opening a `/continue` browser tab would be noise.
// Every failure mode degrades to the splash re-click recovery.
if (isTrueFirstRun && decision.action === 'navigator') {
+ const shareReceiveLogger = getLogger('share-receive');
startFirstRunHandshake({
isFirstRun: () => true,
createServer: (handler) => {
@@ -8128,16 +8159,17 @@ function bootPrimaryInstance(): void {
},
openExternal: (url) => {
void shell.openExternal(url).catch((err) => {
- console.warn('[main] deferred-share openExternal failed', {
- err: err instanceof Error ? err.message : String(err),
- });
+ shareReceiveLogger.warn(
+ { errorKind: err instanceof Error ? err.name : typeof err },
+ 'deferred-share openExternal failed',
+ );
});
},
routeShareUrl: (url) => protocolControl.routeUrl(url),
recordOutcome: (outcome) => recordFirstRunShareHandoff(outcome),
log: {
- warn: (obj, msg) => console.warn(msg, obj),
- info: (obj, msg) => console.info(msg, obj),
+ warn: (obj, msg) => shareReceiveLogger.warn({ ...obj }, msg),
+ info: (obj, msg) => shareReceiveLogger.info({ ...obj }, msg),
},
});
}
diff --git a/packages/desktop/src/main/share-handoff.test.ts b/packages/desktop/src/main/share-handoff.test.ts
index 52e0722c9..c6c25ff95 100644
--- a/packages/desktop/src/main/share-handoff.test.ts
+++ b/packages/desktop/src/main/share-handoff.test.ts
@@ -1,4 +1,6 @@
+import { createServer as createHttpServer, type Server as HttpServer } from 'node:http';
import { describe, expect, test } from 'vitest';
+import fixture from '../../../../test-support/fixtures/share-url-v1-v2.json';
import {
buildContinueUrl,
classifyRedeemRequest,
@@ -13,6 +15,13 @@ import {
resolveContinueBase,
startFirstRunHandshake,
} from './share-handoff.ts';
+import {
+ parseShareUrl,
+ registerProtocolHandler,
+ type ShareNavigatorPayload,
+ type ShareParseResult,
+ type ShareUrlPayload,
+} from './url-scheme.ts';
const NONCE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
const TOKEN = 'AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvdGVjaC1pcG9z';
@@ -33,6 +42,49 @@ describe('nonce', () => {
});
describe('classifyRedeemRequest', () => {
+ test('preserves a maximum canonical v2 token opaquely and rejects its over-limit sibling', () => {
+ expect(
+ classifyRedeemRequest({
+ pathname: '/redeem',
+ token: fixture.bounds.maxCase.token,
+ nonce: NONCE,
+ expectedNonce: NONCE,
+ }),
+ ).toMatchObject({
+ kind: 'redeem',
+ shareUrl: `https://openknowledge.ai/d/${fixture.bounds.maxCase.token}`,
+ });
+ expect(
+ classifyRedeemRequest({
+ pathname: '/redeem',
+ token: fixture.bounds.overLimitToken,
+ nonce: NONCE,
+ expectedNonce: NONCE,
+ }),
+ ).toEqual({ kind: 'invalid' });
+ });
+
+ test('retains the historical v1 handoff ceiling', () => {
+ const atLimit = `AQ${'A'.repeat(4094)}`;
+ const overLimit = `${atLimit}A`;
+ expect(
+ classifyRedeemRequest({
+ pathname: '/redeem',
+ token: atLimit,
+ nonce: NONCE,
+ expectedNonce: NONCE,
+ }).kind,
+ ).toBe('redeem');
+ expect(
+ classifyRedeemRequest({
+ pathname: '/redeem',
+ token: overLimit,
+ nonce: NONCE,
+ expectedNonce: NONCE,
+ }),
+ ).toEqual({ kind: 'invalid' });
+ });
+
test('non-redeem path is ignored (does not burn the nonce)', () => {
expect(
classifyRedeemRequest({
@@ -219,6 +271,122 @@ function harness(over: Partial<FirstRunHandshakeDeps> = {}) {
}
describe('startFirstRunHandshake', () => {
+ test('the real loopback listener routes the exact maximum canonical v2 token unchanged', async () => {
+ const token = fixture.bounds.maxCase.token;
+ expect(token).toHaveLength(3984);
+
+ let server: HttpServer | undefined;
+ let resolveContinueUrl: ((url: string) => void) | undefined;
+ let resolveRoutedUrl: ((url: string) => void) | undefined;
+ const continueUrl = new Promise<string>((resolve) => {
+ resolveContinueUrl = resolve;
+ });
+ const routedUrl = new Promise<string>((resolve) => {
+ resolveRoutedUrl = resolve;
+ });
+ const outcomes: HandoffOutcome[] = [];
+ const normalizedShares: ShareUrlPayload[] = [];
+ const parsedResults: Array<ShareParseResult | null> = [];
+ let resolveRoutedResult!: (result: ShareNavigatorPayload) => void;
+ const routedResult = new Promise<ShareNavigatorPayload>((resolve) => {
+ resolveRoutedResult = resolve;
+ });
+ const protocolControl = registerProtocolHandler({
+ app: {
+ on: () => {},
+ whenReady: () => Promise.resolve(),
+ isPackaged: true,
+ setAsDefaultProtocolClient: () => true,
+ removeAsDefaultProtocolClient: () => true,
+ },
+ focusWindowForProject: () => null,
+ openProject: () => Promise.resolve(null),
+ sendDeepLink: () => {},
+ getAnyReadyWindow: () => null,
+ getInitialArgv: () => [],
+ platform: 'linux',
+ resolveShareTarget: (share) => {
+ normalizedShares.push(share);
+ return Promise.resolve({ kind: 'miss' });
+ },
+ routeShareToNavigator: (result) => resolveRoutedResult(result),
+ });
+
+ startFirstRunHandshake({
+ isFirstRun: () => true,
+ createServer: (handler) => {
+ server = createHttpServer(handler);
+ return server;
+ },
+ openExternal: (url) => resolveContinueUrl?.(url),
+ routeShareUrl: (url) => {
+ resolveRoutedUrl?.(url);
+ parsedResults.push(parseShareUrl(url));
+ protocolControl.routeUrl(url);
+ },
+ recordOutcome: (outcome) => outcomes.push(outcome),
+ generateNonce: () => NONCE,
+ listenerLifetimeMs: 2_000,
+ });
+
+ try {
+ const opened = new URL(await continueUrl);
+ const response = await fetch(
+ `http://127.0.0.1:${opened.searchParams.get('port')}/redeem?${new URLSearchParams({
+ token,
+ nonce: NONCE,
+ })}`,
+ { redirect: 'manual' },
+ );
+
+ expect(response.status).toBe(302);
+ expect(response.headers.get('location')).toBe('https://openknowledge.ai/continue/done');
+ expect(await routedUrl).toBe(`https://openknowledge.ai/d/${token}`);
+ expect(parsedResults).toEqual([
+ {
+ kind: 'ok',
+ source: 'universal-link',
+ dedupKey: `2:1:${fixture.bounds.maxCase.sharedUrl}`,
+ payload: {
+ contentRootDepth: 1,
+ host: 'github.com',
+ owner: 'o',
+ repo: 'r',
+ branch: 'main',
+ repositoryTarget: {
+ kind: 'doc',
+ docPath: `wiki/${fixture.bounds.maxCase.target.docPath}`,
+ },
+ sharedUrl: fixture.bounds.maxCase.sharedUrl,
+ target: fixture.bounds.maxCase.target,
+ },
+ },
+ ]);
+ expect(normalizedShares).toEqual([
+ {
+ contentRootDepth: 1,
+ host: 'github.com',
+ owner: 'o',
+ repo: 'r',
+ branch: 'main',
+ repositoryTarget: {
+ kind: 'doc',
+ docPath: `wiki/${fixture.bounds.maxCase.target.docPath}`,
+ },
+ sharedUrl: fixture.bounds.maxCase.sharedUrl,
+ target: fixture.bounds.maxCase.target,
+ },
+ ]);
+ expect(await routedResult).toEqual({
+ kind: 'launcher-miss',
+ share: normalizedShares[0],
+ });
+ expect(outcomes).toEqual(['redeemed']);
+ } finally {
+ server?.close();
+ }
+ });
+
test('not a first run → records skipped, opens nothing', () => {
const h = harness({ isFirstRun: () => false });
expect(h.outcomes).toEqual(['skipped']);
@@ -319,13 +487,22 @@ describe('startFirstRunHandshake', () => {
});
test('routeShareUrl throwing after response does not propagate — records redeemed', () => {
+ const logs: Array<{ obj: object; msg: string }> = [];
+ const secretPath = '/private/project/wiki/secret.md';
const h = harness({
routeShareUrl: () => {
- throw new Error('downstream error');
+ throw new Error(`downstream error for ${secretPath} token=${TOKEN}`);
},
+ log: { warn: (obj, msg) => logs.push({ obj, msg }) },
});
const res = h.getServer().request(`/redeem?token=${TOKEN}&nonce=${NONCE}`);
expect(res.statusCode).toBe(302);
expect(h.outcomes).toEqual(['redeemed']);
+ expect(JSON.stringify(logs)).not.toContain(secretPath);
+ expect(JSON.stringify(logs)).not.toContain(TOKEN);
+ expect(logs).toContainEqual({
+ obj: { errorKind: 'Error' },
+ msg: '[receive] source=deferred routeShareUrl threw',
+ });
});
});
diff --git a/packages/desktop/src/main/share-handoff.ts b/packages/desktop/src/main/share-handoff.ts
index 8cda03c6b..402148627 100644
--- a/packages/desktop/src/main/share-handoff.ts
+++ b/packages/desktop/src/main/share-handoff.ts
@@ -71,7 +71,8 @@ function isLoopbackHttpUrl(value: string): boolean {
}
/** Upper bound on the redeemed token — matches the web `MAX_TOKEN_LENGTH`. */
-const MAX_TOKEN_LENGTH = 4096;
+const MAX_LEGACY_TOKEN_LENGTH = 4096;
+const MAX_V2_TOKEN_LENGTH = 3984;
/** base64url alphabet — the token is `encodeShareUrl` output. */
const TOKEN_RE = /^[A-Za-z0-9_-]+$/;
@@ -95,9 +96,18 @@ export function nonceMatches(expected: string, candidate: string | null): boolea
}
function isValidToken(token: string | null): token is string {
- return (
- token !== null && token.length > 0 && token.length <= MAX_TOKEN_LENGTH && TOKEN_RE.test(token)
- );
+ if (token === null || token.length === 0) return false;
+ const maxLength = peekShareVersion(token) === 2 ? MAX_V2_TOKEN_LENGTH : MAX_LEGACY_TOKEN_LENGTH;
+ return token.length <= maxLength && TOKEN_RE.test(token);
+}
+
+function peekShareVersion(token: string): number | null {
+ if (token.length < 2) return null;
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
+ const first = alphabet.indexOf(token[0]);
+ const second = alphabet.indexOf(token[1]);
+ if (first < 0 || second < 0) return null;
+ return (first << 2) | (second >>> 4);
}
/** The URL the app opens in the default browser to start the handshake. */
@@ -236,7 +246,14 @@ export function startFirstRunHandshake(deps: FirstRunHandshakeDeps): void {
try {
const parsed = parseRedeemRequestUrl(req.url ?? '/', 'http://127.0.0.1');
decision = classifyRedeemRequest({ ...parsed, expectedNonce: nonce, continueBase });
- } catch {
+ } catch (err) {
+ // Surface the parse-failure kind (bounded) so a malformed redeem request is
+ // diagnosable, matching the errorKind logging on the rest of the receive
+ // path; the outcome is still recorded below as `invalid`.
+ deps.log?.warn(
+ { errorKind: err instanceof Error ? err.name : typeof err },
+ '[receive] source=deferred redeem request parse threw',
+ );
decision = { kind: 'invalid' };
}
@@ -261,7 +278,10 @@ export function startFirstRunHandshake(deps: FirstRunHandshakeDeps): void {
try {
deps.routeShareUrl(decision.shareUrl);
} catch (err) {
- deps.log?.warn({ err }, '[receive] source=deferred routeShareUrl threw');
+ deps.log?.warn(
+ { errorKind: err instanceof Error ? err.name : typeof err },
+ '[receive] source=deferred routeShareUrl threw',
+ );
}
} else {
res.statusCode = 400;
diff --git a/packages/desktop/src/main/url-scheme.test.ts b/packages/desktop/src/main/url-scheme.test.ts
index 62901877a..42f738d70 100644
--- a/packages/desktop/src/main/url-scheme.test.ts
+++ b/packages/desktop/src/main/url-scheme.test.ts
@@ -1,7 +1,38 @@
import { encodeShareUrl } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
+import fixture from '../../../../test-support/fixtures/share-url-v1-v2.json';
+import {
+ frozenV1CustomSchemeOutcome,
+ frozenV1DecodeShareToken,
+} from '../../../../test-support/share/frozen-v1-share-reader.test-helper.ts';
import { parseOpenKnowledgeUrl, parseScreenUrl, parseShareUrl } from './url-scheme.ts';
+/**
+ * The old-app claim is asserted through the SHARED frozen reader, never a
+ * local restatement of it. A second oracle spelled out here would model the
+ * same shipped binary at a different fidelity, and the two would agree only
+ * for whichever inputs the corpus happens to carry.
+ */
+describe('frozen pre-v2 reader compatibility oracle', () => {
+ test.each(fixture.customSchemeCases)('$id keeps its documented old-app outcome', (entry) => {
+ expect(frozenV1CustomSchemeOutcome(entry.uri)).toBe(entry.baseline);
+ });
+
+ test.each(
+ fixture.validShares.filter((entry) => entry.version === 2),
+ )('$id remains unsupported in universal and deferred old-app delivery', (entry) => {
+ expect(frozenV1DecodeShareToken(entry.token)).toEqual({
+ kind: 'unsupported-version',
+ version: 2,
+ });
+ expect(
+ frozenV1DecodeShareToken(
+ new URL(`https://openknowledge.ai/d/${entry.token}`).pathname.slice(3),
+ ),
+ ).toEqual({ kind: 'unsupported-version', version: 2 });
+ });
+});
+
/**
* Pure function — no
* Electron bindings touched at module top, so Bun runs it directly.
@@ -264,17 +295,40 @@ describe('parseOpenKnowledgeUrl — MCP producer/consumer round-trip', () => {
* `parseOpenKnowledgeUrl`).
*/
describe('parseShareUrl — universal-link happy path', () => {
+ test.each(
+ fixture.validShares.filter((entry) => entry.version === 2),
+ )('projects canonical $id to its content-relative target', (entry) => {
+ expect(parseShareUrl(`https://openknowledge.ai/d/${entry.token}`)).toMatchObject({
+ kind: 'ok',
+ source: 'universal-link',
+ payload: {
+ sharedUrl: entry.sharedUrl,
+ target: entry.target,
+ },
+ });
+ });
+
+ test.each(fixture.legacyAliases)('preserves tolerated v1 alias $id', (entry) => {
+ expect(parseShareUrl(`https://openknowledge.ai/d/${entry.token}`)).toMatchObject({
+ kind: 'ok',
+ payload: { sharedUrl: entry.sharedUrl },
+ });
+ });
+
test('parses universal-link URL with main branch', () => {
const encoded = encodeShareUrl('https://github.com/inkeep/playbooks/blob/main/marketing.md');
const result = parseShareUrl(`https://openknowledge.ai/d/${encoded}`);
expect(result).toEqual({
kind: 'ok',
source: 'universal-link',
+ dedupKey: '1:https://github.com/inkeep/playbooks/blob/main/marketing.md',
payload: {
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
+ repositoryTarget: { kind: 'doc', docPath: 'marketing.md' },
sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/marketing.md',
target: { kind: 'doc', docPath: 'marketing.md' },
},
@@ -338,21 +392,20 @@ describe('parseShareUrl — universal-link extensibility (D30 Axis 1+2)', () =>
});
describe('parseShareUrl — universal-link error states', () => {
- test('reports unsupported-version for v2 payload (0x02 byte)', () => {
- // Hand-build a v2 payload: [0x02] + utf-8 bytes of a valid blob URL.
- // Old desktops MUST surface "update" toast, not silent-mis-decode.
- const blobBytes = new TextEncoder().encode('https://github.com/o/r/blob/main/x.md');
- const payload = new Uint8Array(blobBytes.length + 1);
- payload[0] = 0x02;
- payload.set(blobBytes, 1);
- let b64 = '';
- for (const byte of payload) b64 += String.fromCharCode(byte);
- const encoded = btoa(b64).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
- const result = parseShareUrl(`https://openknowledge.ai/d/${encoded}`);
+ test.each(fixture.invalidTokens)('rejects canonical fixture case $id', (entry) => {
+ expect(parseShareUrl(`https://openknowledge.ai/d/${entry.token}`)).toEqual({
+ kind: 'invalid',
+ source: 'universal-link',
+ });
+ });
+
+ test('reports unsupported-version for a future payload', () => {
+ const future = fixture.unsupportedTokens[0];
+ const result = parseShareUrl(`https://openknowledge.ai/d/${future.token}`);
expect(result).toEqual({
kind: 'unsupported-version',
source: 'universal-link',
- version: 2,
+ version: future.version,
});
});
@@ -402,17 +455,30 @@ describe('parseShareUrl — universal-link error states', () => {
});
describe('parseShareUrl — custom-scheme happy path', () => {
+ test('parses the canonical token-only v2 handoff without a second decode', () => {
+ const entry = fixture.validShares.find((item) => item.id === 'v2-one-segment-document');
+ if (!entry) throw new Error('fixture missing v2-one-segment-document');
+ expect(parseShareUrl(`openknowledge://share?token=${entry.token}`)).toMatchObject({
+ kind: 'ok',
+ source: 'custom-scheme',
+ payload: { sharedUrl: entry.sharedUrl, target: entry.target },
+ });
+ });
+
test('parses openknowledge://share?url=<blob-url>', () => {
const sharedUrl = 'https://github.com/inkeep/playbooks/blob/main/marketing.md';
const result = parseShareUrl(`openknowledge://share?url=${encodeURIComponent(sharedUrl)}`);
expect(result).toEqual({
kind: 'ok',
source: 'custom-scheme',
+ dedupKey: `1:${sharedUrl}`,
payload: {
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
+ repositoryTarget: { kind: 'doc', docPath: 'marketing.md' },
sharedUrl,
target: { kind: 'doc', docPath: 'marketing.md' },
},
@@ -440,6 +506,24 @@ describe('parseShareUrl — custom-scheme happy path', () => {
});
describe('parseShareUrl — custom-scheme error states', () => {
+ test.each(
+ fixture.customSchemeCases.filter((entry) =>
+ ['v2-token-plus-url', 'v2-duplicate-token', 'v2-empty-token'].includes(entry.id),
+ ),
+ )('rejects authoritative malformed token form $id', (entry) => {
+ expect(parseShareUrl(entry.uri)).toEqual({ kind: 'invalid', source: 'custom-scheme' });
+ });
+
+ test('reports unsupported-version for a future payload token', () => {
+ const future = fixture.unsupportedTokens[0];
+ const result = parseShareUrl(`openknowledge://share?token=${future.token}`);
+ expect(result).toEqual({
+ kind: 'unsupported-version',
+ source: 'custom-scheme',
+ version: future.version,
+ });
+ });
+
test('reports invalid when url param is missing', () => {
const result = parseShareUrl('openknowledge://share');
expect(result).toEqual({ kind: 'invalid', source: 'custom-scheme' });
@@ -527,9 +611,37 @@ describe('parseShareUrl — not-a-share-url (returns null, caller falls through)
expect(parseShareUrl('not a url')).toBeNull();
});
- test('returns null for null-byte smuggle attempts', () => {
- expect(parseShareUrl('https://openknowledge.ai/d/abc\x00')).toBeNull();
- expect(parseShareUrl('https://openknowledge.ai/d/abc%00def')).toBeNull();
+ test('classifies malformed share authorities as terminal invalid without claiming lookalikes', () => {
+ for (const input of [
+ 'https://openknowledge.ai:bad/d/secret-token',
+ 'https://www.openknowledge.ai:99999/d/secret-token',
+ ]) {
+ expect(parseShareUrl(input)).toEqual({ kind: 'invalid', source: 'universal-link' });
+ }
+ expect(parseShareUrl('openknowledge://share:bad?token=secret-token')).toEqual({
+ kind: 'invalid',
+ source: 'custom-scheme',
+ });
+
+ expect(parseShareUrl('https://example.com:bad/d/secret-token')).toBeNull();
+ expect(parseShareUrl('https://[email protected]:bad/d/secret-token')).toBeNull();
+ expect(parseShareUrl('openknowledge://shareholder:bad?token=secret-token')).toBeNull();
+ });
+
+ test('classifies share-shaped null-byte smuggle attempts as terminal invalid', () => {
+ expect(parseShareUrl('https://openknowledge.ai/d/abc\x00')).toEqual({
+ kind: 'invalid',
+ source: 'universal-link',
+ });
+ expect(parseShareUrl('https://openknowledge.ai/d/abc%00def')).toEqual({
+ kind: 'invalid',
+ source: 'universal-link',
+ });
+ expect(parseShareUrl('openknowledge://share?token=abc%00def')).toEqual({
+ kind: 'invalid',
+ source: 'custom-scheme',
+ });
+ expect(parseShareUrl('openknowledge://open?project=/tmp%00secret')).toBeNull();
});
});
diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.ts
index 4b4d3cbed..4e5aa0d82 100644
--- a/packages/desktop/src/main/url-scheme.ts
+++ b/packages/desktop/src/main/url-scheme.ts
@@ -87,7 +87,7 @@ interface ParsedOpenKnowledgeUrl {
*/
const SHARE_UNIVERSAL_LINK_HOSTS = new Set(['openknowledge.ai', 'www.openknowledge.ai']);
-/** Universal-link path prefix that carries the v1 base64url-encoded payload. */
+/** Universal-link path prefix that carries a versioned base64url payload. */
const SHARE_UNIVERSAL_LINK_PATH_PREFIX = '/d/';
/**
@@ -128,7 +128,13 @@ export type ShareUrlSource = 'universal-link' | 'custom-scheme';
* legacy `open` action.
*/
export type ShareParseResult =
- | { readonly kind: 'ok'; readonly source: ShareUrlSource; readonly payload: ShareUrlPayload }
+ | {
+ readonly kind: 'ok';
+ readonly source: ShareUrlSource;
+ readonly payload: ShareUrlPayload;
+ /** Version-aware semantic identity for near-simultaneous delivery dedup. */
+ readonly dedupKey: string;
+ }
| {
readonly kind: 'unsupported-version';
readonly source: ShareUrlSource;
@@ -136,6 +142,34 @@ export type ShareParseResult =
}
| { readonly kind: 'invalid'; readonly source: ShareUrlSource };
+function classifyShareUrlSource(url: URL): ShareUrlSource | null {
+ if (url.protocol === 'openknowledge:' && url.hostname === 'share') return 'custom-scheme';
+ if (
+ (url.protocol === 'https:' || url.protocol === 'http:') &&
+ SHARE_UNIVERSAL_LINK_HOSTS.has(url.hostname) &&
+ url.pathname.startsWith(SHARE_UNIVERSAL_LINK_PATH_PREFIX)
+ ) {
+ return 'universal-link';
+ }
+ return null;
+}
+
+/**
+ * Recognize a share route before WHATWG parsing when a malformed authority
+ * makes `new URL()` throw. Keep this deliberately narrower than a general URL
+ * parser: the known host must be exact, an optional malformed port cannot
+ * contain userinfo, and universal links must still claim the `/d/` route.
+ */
+function classifyRawShareUrlSource(input: string): ShareUrlSource | null {
+ if (/^openknowledge:\/\/share(?::[^/?#@]*)?(?:[/?#]|$)/i.test(input)) {
+ return 'custom-scheme';
+ }
+ if (/^https?:\/\/(?:www\.)?openknowledge\.ai(?::[^/?#@]*)?\/d\//i.test(input)) {
+ return 'universal-link';
+ }
+ return null;
+}
+
/**
* Common share fields carried on every `ShareDeepLinkPayload` variant that
* successfully decoded. Aliases the canonical `OkSharePayloadFields` from
@@ -179,13 +213,10 @@ export type ShareNavigatorPayload = Extract<
/**
* Parse + validate a share URL. Handles both shapes:
- * - Universal link: `https://openknowledge.ai/d/<base64url([0x01]||blob-url)>`
- * (and `www.openknowledge.ai`) — base64url-decode, version-byte dispatch,
- * blob-URL shape check. Tolerates unknown query params and fragments for
- * forward-compatible payload extensibility.
- * - Custom scheme: `openknowledge://share?url=<urlencoded(<blob-url>)>` —
- * URL-decode the `url` param directly (no version byte; the custom-scheme
- * path is the immediate-handoff path, never persisted to marketing copy).
+ * - Universal link: `https://openknowledge.ai/d/<versioned-token>` (and the
+ * `www` host), with permanent tolerant v1 and strict canonical v2 decode.
+ * - Custom scheme: v2 uses `token=<canonical-v2-token>`; v1 keeps the
+ * historical `url=<urlencoded-github-url>` form.
*
* Returns `null` if the input is neither shape — caller falls through to
* `parseOpenKnowledgeUrl` for the legacy `open` action.
@@ -194,26 +225,25 @@ export type ShareNavigatorPayload = Extract<
*/
export function parseShareUrl(input: string): ShareParseResult | null {
if (typeof input !== 'string' || input.length === 0) return null;
- // Null-byte defense mirrors `parseOpenKnowledgeUrl`. Reject before `new URL`
- // because `decodeURIComponent('%00')` produces `'\x00'`, which can truncate
- // paths in downstream C libraries.
- if (input.includes('\x00') || /%00/i.test(input)) return null;
+ const rawSource = classifyRawShareUrlSource(input);
+ // Never forward a null byte to path consumers. A share-shaped input remains
+ // a terminal share failure so the generic URL fallback cannot log it raw.
+ if (input.includes('\x00') || /%00/i.test(input)) {
+ return rawSource === null ? null : { kind: 'invalid', source: rawSource };
+ }
let url: URL;
try {
url = new URL(input);
} catch {
- return null;
+ return rawSource === null ? null : { kind: 'invalid', source: rawSource };
}
- if (url.protocol === 'openknowledge:' && url.hostname === 'share') {
+ const source = classifyShareUrlSource(url);
+ if (source === 'custom-scheme') {
return parseShareCustomScheme(url);
}
- if (
- (url.protocol === 'https:' || url.protocol === 'http:') &&
- SHARE_UNIVERSAL_LINK_HOSTS.has(url.hostname) &&
- url.pathname.startsWith(SHARE_UNIVERSAL_LINK_PATH_PREFIX)
- ) {
+ if (source === 'universal-link') {
return parseShareUniversalLink(url);
}
return null;
@@ -233,7 +263,7 @@ function parseShareUniversalLink(url: URL): ShareParseResult {
if (encoded === undefined || encoded.length === 0) {
return { kind: 'invalid', source: 'universal-link' };
}
- let decoded: { sharedUrl: string };
+ let decoded: ReturnType<typeof decodeShareUrl>;
try {
decoded = decodeShareUrl(encoded);
} catch (err) {
@@ -251,20 +281,37 @@ function parseShareUniversalLink(url: URL): ShareParseResult {
// escape to the routing layer.
return { kind: 'invalid', source: 'universal-link' };
}
- return finalizeShareResult(decoded.sharedUrl, 'universal-link');
+ return finalizeDecodedShare(decoded, 'universal-link');
}
function parseShareCustomScheme(url: URL): ShareParseResult {
- // The custom-scheme path carries the URL directly without the
- // version byte. The custom scheme is the immediate-handoff path (splash
- // page → OK) and never appears in marketing copy, so version-dispatch
- // would only add complexity for no benefit.
- const rawSharedUrl = url.searchParams.get('url');
- if (!rawSharedUrl) {
+ const tokens = url.searchParams.getAll('token');
+ const legacyUrls = url.searchParams.getAll('url');
+
+ // Presence is authoritative: malformed token forms never fall through to
+ // the legacy URL parameter, because doing so would let an ambiguous handoff
+ // silently change wire-version semantics.
+ if (tokens.length > 0) {
+ if (tokens.length !== 1 || tokens[0] === '' || legacyUrls.length !== 0) {
+ return { kind: 'invalid', source: 'custom-scheme' };
+ }
+ try {
+ const decoded = decodeShareUrl(tokens[0]);
+ if (decoded.version !== 2) return { kind: 'invalid', source: 'custom-scheme' };
+ return finalizeDecodedShare(decoded, 'custom-scheme');
+ } catch (err) {
+ if (err instanceof UnsupportedShareVersionError) {
+ return { kind: 'unsupported-version', source: 'custom-scheme', version: err.version };
+ }
+ return { kind: 'invalid', source: 'custom-scheme' };
+ }
+ }
+
+ if (legacyUrls.length !== 1 || legacyUrls[0] === '') {
return { kind: 'invalid', source: 'custom-scheme' };
}
// URLSearchParams.get already URL-decodes; no further decode needed.
- return finalizeShareResult(rawSharedUrl, 'custom-scheme');
+ return finalizeV1ShareResult(legacyUrls[0], 'custom-scheme');
}
/**
@@ -274,7 +321,35 @@ function parseShareCustomScheme(url: URL): ShareParseResult {
*/
const MAX_SHARED_URL_LENGTH = 4096;
-function finalizeShareResult(sharedUrl: string, source: ShareUrlSource): ShareParseResult {
+function finalizeDecodedShare(
+ decoded: ReturnType<typeof decodeShareUrl>,
+ source: ShareUrlSource,
+): ShareParseResult {
+ if (decoded.version === 1) return finalizeV1ShareResult(decoded.sharedUrl, source);
+
+ const repositoryPath = decoded.source.targetSegments.join('/');
+ const repositoryTarget: ShareTarget =
+ decoded.source.kind === 'doc'
+ ? { kind: 'doc', docPath: repositoryPath }
+ : { kind: 'folder', folderPath: repositoryPath };
+ return {
+ kind: 'ok',
+ source,
+ dedupKey: `2:${decoded.contentRootDepth}:${decoded.sharedUrl}`,
+ payload: {
+ contentRootDepth: decoded.contentRootDepth,
+ host: decoded.source.host,
+ owner: decoded.source.owner,
+ repo: decoded.source.repo,
+ branch: decoded.source.branch,
+ repositoryTarget,
+ sharedUrl: decoded.sharedUrl,
+ target: decoded.target,
+ },
+ };
+}
+
+function finalizeV1ShareResult(sharedUrl: string, source: ShareUrlSource): ShareParseResult {
if (typeof sharedUrl !== 'string' || sharedUrl.length === 0) {
return { kind: 'invalid', source };
}
@@ -299,11 +374,14 @@ function finalizeShareResult(sharedUrl: string, source: ShareUrlSource): SharePa
return {
kind: 'ok',
source,
+ dedupKey: `1:${sharedUrl}`,
payload: {
+ contentRootDepth: null,
host: parsed.host,
owner: parsed.owner,
repo: parsed.repo,
branch: parsed.branch,
+ repositoryTarget: target,
sharedUrl,
target,
},
@@ -555,7 +633,12 @@ interface ProtocolHandlerDeps {
openProject(
projectPath: string,
opts?: {
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ };
pendingBranch?: string | null;
/**
* Multi-candidate hint forwarded into `ok:deep-link` so the
@@ -599,6 +682,8 @@ interface ProtocolHandlerDeps {
branch?: string | null;
multiCandidate?: boolean;
targetMissing?: boolean;
+ repositoryPath?: string;
+ contentRootDepth?: number;
},
): void;
/**
@@ -781,8 +866,8 @@ interface ProtocolHandlerControl {
}
/**
- * Window within which the same share target (keyed on its canonical
- * `sharedUrl`) routes at most once. Defeats the double-delivery race where a
+ * Window within which the same semantic versioned share routes at most once.
+ * Defeats the double-delivery race where a
* first-run loopback redemption and a simultaneous splash "Open in Open
* Knowledge" re-click both deliver the same share.
*/
@@ -924,17 +1009,16 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
* renderer surfaces these as sonner toasts, no resolution required.
*/
const broadcastShareToast = (
- url: string,
payload: { readonly kind: 'unsupported-version' } | { readonly kind: 'invalid' },
): void => {
const sendShare = deps.sendShareDeepLink;
if (!sendShare) {
- deps.log?.warn({ url }, '[receive] sendShareDeepLink dep missing — share dropped');
+ deps.log?.warn({}, '[receive] sendShareDeepLink dep missing — share dropped');
return;
}
const target = deps.getFocusedWindow?.() ?? deps.getAnyReadyWindow();
if (!target) {
- deps.log?.warn({ url }, '[receive] no target window — share dropped');
+ deps.log?.warn({}, '[receive] no target window — share dropped');
return;
}
sendShare(target, payload);
@@ -957,12 +1041,8 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
* directly. Otherwise spawn the editor with `pendingShareBranchSwitch`
* threaded so window-manager's dom-ready hook delivers after mount.
*/
- const dispatchResolvedShare = (
- url: string,
- share: ShareUrlPayload,
- selection: CandidateSelection,
- ): void => {
- deps.log?.info?.({ url, selection: selection.kind }, '[receive] action=routed');
+ const dispatchResolvedShare = (share: ShareUrlPayload, selection: CandidateSelection): void => {
+ deps.log?.info?.({ selection: selection.kind }, '[receive] action=routed');
// Degrade-to-Navigator for the openProject null/reject paths below. Mirrors
// the explicit dep-check the direct-dispatch cases use (branch-match-non-ok
// / miss): when `routeShareToNavigator` is unwired the degrade is logged,
@@ -989,6 +1069,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// window with an early return BEFORE its pendingDeepLinkTarget gate, so
// relying on openProject alone drops the nav on the warm case.) No panel.
const targetPath = shareTargetPath(share.target);
+ const repositoryPath = shareTargetPath(share.repositoryTarget);
// Kind-aware target-existence gate: confirm the share's target exists
// on the candidate's checked-out branch before dispatch. A stale branch
// (target added on the remote but not yet fetched) would otherwise open
@@ -1001,11 +1082,14 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
const isContentRoot = share.target.kind === 'folder' && targetPath === '';
const targetMissing =
!isContentRoot &&
- deps.checkShareTargetExists?.(selection.candidate.path, share.target.kind, targetPath) ===
- 'missing';
+ deps.checkShareTargetExists?.(
+ selection.candidate.path,
+ share.repositoryTarget.kind,
+ repositoryPath,
+ ) === 'missing';
if (targetMissing) {
deps.log?.warn(
- { url, project: selection.candidate.path },
+ { targetKind: share.repositoryTarget.kind },
'[receive] target_check=missing — share target not on checked-out branch; dispatching with in-context toast',
);
}
@@ -1016,6 +1100,10 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
kind: share.target.kind,
branch: share.branch,
multiCandidate: selection.multiCandidate,
+ repositoryPath,
+ ...(share.contentRootDepth === null
+ ? {}
+ : { contentRootDepth: share.contentRootDepth }),
// Only carry the flag when set — keeps the common (present) case's
// payload identical to the pre-gate shape.
...(targetMissing ? { targetMissing: true } : {}),
@@ -1024,7 +1112,14 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
}
void deps
.openProject(selection.candidate.path, {
- pendingDeepLinkTarget: { kind: share.target.kind, path: targetPath },
+ pendingDeepLinkTarget: {
+ kind: share.target.kind,
+ path: targetPath,
+ repositoryPath,
+ ...(share.contentRootDepth === null
+ ? {}
+ : { contentRootDepth: share.contentRootDepth }),
+ },
pendingBranch: share.branch,
pendingMultiCandidate: selection.multiCandidate,
...(targetMissing ? { pendingTargetMissing: true } : {}),
@@ -1036,7 +1131,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// gets clone/locate options rather than a contextless launcher.
if (win === null) {
degradeToLauncherMiss(
- { url, project: selection.candidate.path },
+ {},
'[receive] openProject(branch-match-ok) returned null — degrading to launcher-miss',
);
}
@@ -1044,9 +1139,8 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
.catch((err) => {
degradeToLauncherMiss(
{
- url,
- err: err instanceof Error ? err.message : String(err),
- project: selection.candidate.path,
+ errorKind: err instanceof Error ? err.name : typeof err,
+ errorCode: err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined,
},
'[receive] openProject(branch-match-ok) failed — degrading to launcher-miss',
);
@@ -1076,7 +1170,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// matching the explicit dep-checks in branch-match-non-ok / miss,
// then fall through so the window is at least focused.
deps.log?.warn(
- { url, project: selection.anchor.path },
+ {},
'[receive] sendShareDeepLink dep missing — branch-switch payload not delivered to open window',
);
}
@@ -1085,7 +1179,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
.then((win) => {
if (win === null) {
degradeToLauncherMiss(
- { url, project: selection.anchor.path },
+ {},
'[receive] openProject(branch-switch) returned null — degrading to launcher-miss',
);
}
@@ -1093,9 +1187,8 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
.catch((err) => {
degradeToLauncherMiss(
{
- url,
- err: err instanceof Error ? err.message : String(err),
- project: selection.anchor.path,
+ errorKind: err instanceof Error ? err.name : typeof err,
+ errorCode: err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined,
},
'[receive] openProject(branch-switch) failed — degrading to launcher-miss',
);
@@ -1106,7 +1199,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
const routeToNav = deps.routeShareToNavigator;
if (!routeToNav) {
deps.log?.warn(
- { url },
+ {},
'[receive] routeShareToNavigator dep missing — launcher-consent dropped',
);
return;
@@ -1122,10 +1215,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
case 'miss': {
const routeToNav = deps.routeShareToNavigator;
if (!routeToNav) {
- deps.log?.warn(
- { url },
- '[receive] routeShareToNavigator dep missing — launcher-miss dropped',
- );
+ deps.log?.warn({}, '[receive] routeShareToNavigator dep missing — launcher-miss dropped');
return;
}
routeToNav({ kind: 'launcher-miss', share });
@@ -1136,49 +1226,70 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// core without a matching routing case would land here at runtime.
const _exhaustive: never = selection;
deps.log?.warn(
- { url, selection: (_exhaustive as { kind: string }).kind },
+ { selection: (_exhaustive as { kind: string }).kind },
'[receive] unknown CandidateSelection kind — share dropped',
);
}
}
};
- const routeShare = (url: string, result: ShareParseResult): void => {
- // Diagnostic log first — fires for every share URL the handler sees,
- // including the silent-drop-no-window edge case below. Bracket-prefix
- // namespace per parent spec §6 non-functional / logging conventions.
- if (result.kind === 'unsupported-version') {
- deps.log?.warn(
- { source: result.source, result: result.kind, version: result.version },
- '[receive] action=url-parse',
- );
+ const routeShare = (result: ShareParseResult): void => {
+ // Diagnostic log first so even silent-drop and no-window outcomes remain
+ // observable without recording the raw share URL.
+ const diagnostic =
+ result.kind === 'ok'
+ ? {
+ source: result.source,
+ result: result.kind,
+ codecVersion:
+ result.payload.contentRootDepth !== null ? ('v2' as const) : ('v1' as const),
+ targetKind: result.payload.target.kind,
+ rootScope:
+ result.payload.contentRootDepth !== null ? ('nested' as const) : ('unknown' as const),
+ }
+ : {
+ source: result.source,
+ result: result.kind,
+ codecVersion:
+ result.kind === 'unsupported-version'
+ ? ('unsupported' as const)
+ : ('unknown' as const),
+ targetKind: 'unknown' as const,
+ rootScope: 'unknown' as const,
+ };
+ if (result.kind === 'ok') {
+ // A successful parse is routine — keep it off the warn channel operators
+ // alert on, matching the info? entry diagnostics used elsewhere here.
+ deps.log?.info?.(diagnostic, '[receive] action=url-parse');
+ } else if (result.kind === 'unsupported-version') {
+ deps.log?.warn({ ...diagnostic, version: result.version }, '[receive] action=url-parse');
} else {
- deps.log?.warn({ source: result.source, result: result.kind }, '[receive] action=url-parse');
+ deps.log?.warn(diagnostic, '[receive] action=url-parse');
}
if (result.kind !== 'ok') {
// Toast-only variants — send to any window via the legacy broadcast
// path. No resolution required.
- broadcastShareToast(url, { kind: result.kind });
+ broadcastShareToast({ kind: result.kind });
return;
}
// Near-simultaneous-duplicate suppression. A redeemed deferred share and a
// manual splash re-click for the same target arrive as two `ok` shares with
// the same `sharedUrl`; route the first, drop the second within the window.
const now = deps.now ? deps.now() : Date.now();
- const last = shareDedup.get(result.payload.sharedUrl);
+ const last = shareDedup.get(result.dedupKey);
if (last !== undefined && now - last < SHARE_DEDUP_WINDOW_MS) {
deps.log?.warn({ source: result.source, result: result.kind }, '[receive] action=deduped');
return;
}
- shareDedup.set(result.payload.sharedUrl, now);
- for (const [url, ts] of shareDedup) {
- if (now - ts >= SHARE_DEDUP_WINDOW_MS) shareDedup.delete(url);
+ shareDedup.set(result.dedupKey, now);
+ for (const [key, ts] of shareDedup) {
+ if (now - ts >= SHARE_DEDUP_WINDOW_MS) shareDedup.delete(key);
}
const resolver = deps.resolveShareTarget;
if (!resolver) {
// Resolution is the decision authority for an `ok` share — without it
// there is no target to route to. Production main always wires it.
- deps.log?.warn({ url }, '[receive] resolveShareTarget dep missing — share dropped');
+ deps.log?.warn({}, '[receive] resolveShareTarget dep missing — share dropped');
return;
}
// Non-github.com shares must clear the foreign-host trust gate before
@@ -1188,7 +1299,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
if (!gate) {
// Fail-closed: no gate wired ⇒ drop the foreign-host share.
deps.log?.warn(
- { url, host: result.payload.host },
+ { host: result.payload.host },
'[receive] foreign-host share with no gate — dropped',
);
return;
@@ -1197,24 +1308,27 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
(decision) => {
if (decision === 'proceed') {
void resolver(result.payload).then(
- (selection) => dispatchResolvedShare(url, result.payload, selection),
- () => dispatchResolvedShare(url, result.payload, { kind: 'miss' }),
+ (selection) => dispatchResolvedShare(result.payload, selection),
+ () => dispatchResolvedShare(result.payload, { kind: 'miss' }),
);
} else {
deps.log?.info?.(
- { url, host: result.payload.host, decision },
+ { host: result.payload.host, decision },
'[receive] foreign-host share not proceeded',
);
}
},
(err) => {
- deps.log?.warn({ err, url }, '[receive] foreign-host gate rejected — share dropped');
+ deps.log?.warn(
+ { errorKind: err instanceof Error ? err.name : typeof err },
+ '[receive] foreign-host gate rejected — share dropped',
+ );
},
);
return;
}
void resolver(result.payload).then(
- (selection) => dispatchResolvedShare(url, result.payload, selection),
+ (selection) => dispatchResolvedShare(result.payload, selection),
(err) => {
// `selectCandidate` degrades to `miss` internally on I/O failure, so a
// reject here is a near-unreachable defense-in-depth path. Degrade it
@@ -1222,10 +1336,10 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// gets a forward path (clone / locate manually) rather than a silent
// drop, uniform with how resolution itself handles failure.
deps.log?.warn(
- { err, url },
+ { errorKind: err instanceof Error ? err.name : typeof err },
'[receive] resolveShareTarget rejected — degrading to Navigator (miss)',
);
- dispatchResolvedShare(url, result.payload, { kind: 'miss' });
+ dispatchResolvedShare(result.payload, { kind: 'miss' });
},
);
};
@@ -1254,7 +1368,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
const routeUrl = (url: string): void => {
const share = parseShareUrl(url);
if (share !== null) {
- routeShare(url, share);
+ routeShare(share);
return;
}
const screen = parseScreenUrl(url);
@@ -1283,7 +1397,7 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
const parsed = parseOpenKnowledgeUrl(url);
if (!parsed) {
// Silent-drop → single warn log line. No error dialog.
- deps.log?.warn({ url }, '[url-scheme] dropped malformed URL');
+ deps.log?.warn({}, '[url-scheme] dropped malformed URL');
return;
}
const existing = deps.focusWindowForProject(parsed.project);
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 2339f1683..bb872cd33 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -414,7 +414,12 @@ interface CreateProjectWindowOpts {
* the bridge contract's `pendingDeepLinkTarget` so the index.ts seam
* passes it straight through without decomposing into separate fields.
*/
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ };
/**
* Optional share branch carried alongside `pendingDeepLinkTarget`. Threaded
* into the same `dom-ready` deep-link IPC so the renderer's deep-link
@@ -2092,6 +2097,12 @@ export class WindowManager {
kind,
branch,
multiCandidate,
+ ...(opts.pendingDeepLinkTarget.repositoryPath === undefined
+ ? {}
+ : { repositoryPath: opts.pendingDeepLinkTarget.repositoryPath }),
+ ...(opts.pendingDeepLinkTarget.contentRootDepth === undefined
+ ? {}
+ : { contentRootDepth: opts.pendingDeepLinkTarget.contentRootDepth }),
// Only carry the flag when set — keeps the common (present) case's
// payload identical to the pre-gate shape.
...(opts.pendingTargetMissing === true ? { targetMissing: true } : {}),
@@ -2760,7 +2771,12 @@ export class WindowManager {
canonicalKey: string;
projectName: string;
lock: ServerLockMetadataLike;
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ };
pendingBranch?: string | null;
pendingMultiCandidate?: boolean;
pendingTargetMissing?: boolean;
@@ -2845,6 +2861,12 @@ export class WindowManager {
kind,
branch,
multiCandidate,
+ ...(pendingDeepLinkTarget.repositoryPath === undefined
+ ? {}
+ : { repositoryPath: pendingDeepLinkTarget.repositoryPath }),
+ ...(pendingDeepLinkTarget.contentRootDepth === undefined
+ ? {}
+ : { contentRootDepth: pendingDeepLinkTarget.contentRootDepth }),
...(pendingTargetMissing === true ? { targetMissing: true } : {}),
});
}
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 770fbbc03..4cfc85710 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -264,7 +264,12 @@ interface ProjectOpenRequest {
* `pendingDeepLinkTarget` (cold spawn) and `sendDeepLink` (warm-focus).
* Mirrors the `openknowledge://open?project=&doc=` plumbing.
*/
- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };
+ pendingDeepLinkTarget?: {
+ kind: 'doc' | 'folder';
+ path: string;
+ repositoryPath?: string;
+ contentRootDepth?: number;
+ };
/**
* Optional share branch riding alongside `pendingDeepLinkTarget` so the
* renderer can detect branch mismatches on the share-receive Path 2.
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 7313299a0..8b6d65ba9 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -142,6 +142,10 @@ export interface EventChannels {
* opening a blank editor. Absent / `false` → normal navigation.
*/
targetMissing?: boolean;
+ /** URL-derived repository path for version-correct follow-up probes. */
+ repositoryPath?: string;
+ /** Present only for v2 rename-result deprojection. */
+ contentRootDepth?: number;
};
};
/**
diff --git a/packages/desktop/tests/main/url-scheme-handler.test.ts b/packages/desktop/tests/main/url-scheme-handler.test.ts
index ee8c4361d..a565cbcf2 100644
--- a/packages/desktop/tests/main/url-scheme-handler.test.ts
+++ b/packages/desktop/tests/main/url-scheme-handler.test.ts
@@ -2,6 +2,7 @@ import type { Candidate, CandidateSelection } from '@inkeep/open-knowledge-core'
import { encodeShareUrl } from '@inkeep/open-knowledge-core';
import type { Mock } from 'vitest';
import { beforeEach, describe, expect, test, vi } from 'vitest';
+import shareFixture from '../../../../test-support/fixtures/share-url-v1-v2.json';
import type {
ForeignHostDecision,
ScreenTarget,
@@ -377,6 +378,38 @@ describe('registerProtocolHandler — deferred-share routeUrl + dedup', () => {
await flushPromises();
expect(resolveShareTarget).toHaveBeenCalledTimes(2);
});
+
+ test('does not dedup v1 and v2 when the source URL text is identical', async () => {
+ env.readyWindow = { id: 'pre-existing' };
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const control = registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ resolveShareTarget,
+ routeShareToNavigator: vi.fn(() => {}),
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ now: () => 1_000_000,
+ });
+ env.app.resolveReady();
+ await flushPromises();
+
+ const sharedUrl = 'https://github.com/o/r/blob/main/wiki/x.md';
+ control.routeUrl(`https://openknowledge.ai/d/${encodeShareUrl(sharedUrl)}`);
+ control.routeUrl(`https://openknowledge.ai/d/${encodeShareUrl(sharedUrl, 1)}`);
+ await flushPromises();
+ await flushPromises();
+
+ expect(resolveShareTarget).toHaveBeenCalledTimes(2);
+ expect(resolveShareTarget.mock.calls[0]?.[0]).toMatchObject({
+ target: { kind: 'doc', docPath: 'wiki/x.md' },
+ });
+ expect(resolveShareTarget.mock.calls[1]?.[0]).toMatchObject({
+ target: { kind: 'doc', docPath: 'x.md' },
+ });
+ });
});
describe('registerProtocolHandler — foreign-host trust gate', () => {
@@ -997,10 +1030,12 @@ describe('registerProtocolHandler — share-flow routing', () => {
// The custom-scheme URL is parsed and reaches main-side resolution.
expect(resolveShareTarget).toHaveBeenCalledTimes(1);
expect(resolveShareTarget).toHaveBeenCalledWith({
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
+ repositoryTarget: { kind: 'doc', docPath: 'x.md' },
sharedUrl: blobUrl,
target: { kind: 'doc', docPath: 'x.md' },
});
@@ -1029,26 +1064,21 @@ describe('registerProtocolHandler — share-flow routing', () => {
env.app.resolveReady();
await flushPromises();
- // Hand-build v2 payload (0x02 leading byte) — older clients MUST surface
- // an "update" toast, not a silent mis-decode.
- const blobBytes = new TextEncoder().encode('https://github.com/o/r/blob/main/x.md');
- const v2 = new Uint8Array(blobBytes.length + 1);
- v2[0] = 0x02;
- v2.set(blobBytes, 1);
- let raw = '';
- for (const b of v2) raw += String.fromCharCode(b);
- const encoded = btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
- env.app.fireOpenUrl(`https://openknowledge.ai/d/${encoded}`);
+ env.app.fireOpenUrl('https://openknowledge.ai/d/AwABAg');
await flushPromises();
expect(sendShareDeepLink).toHaveBeenCalledWith(focusedWin, { kind: 'unsupported-version' });
- expect(
- warnLog.some(
- (entry) =>
- entry.msg.includes('[receive] action=url-parse') &&
- (entry.obj as { result?: string }).result === 'unsupported-version',
- ),
- ).toBe(true);
+ expect(warnLog).toContainEqual({
+ obj: {
+ source: 'universal-link',
+ result: 'unsupported-version',
+ codecVersion: 'unsupported',
+ targetKind: 'unknown',
+ rootScope: 'unknown',
+ version: 3,
+ },
+ msg: '[receive] action=url-parse',
+ });
});
test('dispatches invalid payload + logs [receive] for corrupt base64', async () => {
@@ -1076,13 +1106,128 @@ describe('registerProtocolHandler — share-flow routing', () => {
await flushPromises();
expect(sendShareDeepLink).toHaveBeenCalledWith(focusedWin, { kind: 'invalid' });
- expect(
- warnLog.some(
- (entry) =>
- entry.msg.includes('[receive] action=url-parse') &&
- (entry.obj as { result?: string }).result === 'invalid',
- ),
- ).toBe(true);
+ expect(warnLog).toContainEqual({
+ obj: {
+ source: 'universal-link',
+ result: 'invalid',
+ codecVersion: 'unknown',
+ targetKind: 'unknown',
+ rootScope: 'unknown',
+ },
+ msg: '[receive] action=url-parse',
+ });
+ expect(JSON.stringify(warnLog)).not.toContain('!!!not-base64!!!');
+ });
+
+ test('malformed share-shaped and lookalike authority inputs keep logs scrubbed', async () => {
+ const env = makeEnv();
+ const focusedWin: FakeWindowHandle = { id: 'focused' };
+ env.readyWindow = focusedWin;
+ const warnLog: Array<{ obj: object; msg: string }> = [];
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const secret = 'SECRET-MALFORMED-SHARE';
+
+ registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ sendShareDeepLink,
+ getFocusedWindow: () => focusedWin,
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ });
+ env.app.resolveReady();
+ await flushPromises();
+
+ env.app.fireOpenUrl(`https://openknowledge.ai/d/${secret}%00PATH`);
+ env.app.fireOpenUrl(`openknowledge://share?token=${secret}%00`);
+ env.app.fireOpenUrl(`https://openknowledge.ai:bad/d/${secret}`);
+ env.app.fireOpenUrl(`https://www.openknowledge.ai:99999/d/${secret}`);
+ env.app.fireOpenUrl(`openknowledge://share:bad?token=${secret}`);
+ env.app.fireOpenUrl(`https://openknowledge.ai%00/d/${secret}`);
+ env.app.fireOpenUrl(`https://openknowledge.ai./d/${secret}`);
+ await flushPromises();
+
+ expect(sendShareDeepLink).toHaveBeenCalledTimes(5);
+ expect(sendShareDeepLink).toHaveBeenNthCalledWith(1, focusedWin, { kind: 'invalid' });
+ expect(sendShareDeepLink).toHaveBeenNthCalledWith(2, focusedWin, { kind: 'invalid' });
+ expect(sendShareDeepLink).toHaveBeenNthCalledWith(3, focusedWin, { kind: 'invalid' });
+ expect(sendShareDeepLink).toHaveBeenNthCalledWith(4, focusedWin, { kind: 'invalid' });
+ expect(sendShareDeepLink).toHaveBeenNthCalledWith(5, focusedWin, { kind: 'invalid' });
+ expect(JSON.stringify(warnLog)).not.toContain(secret);
+ expect(warnLog.filter(({ msg }) => msg === '[url-scheme] dropped malformed URL')).toEqual([
+ { obj: {}, msg: '[url-scheme] dropped malformed URL' },
+ { obj: {}, msg: '[url-scheme] dropped malformed URL' },
+ ]);
+ expect(warnLog).toContainEqual({
+ obj: {
+ source: 'universal-link',
+ result: 'invalid',
+ codecVersion: 'unknown',
+ targetKind: 'unknown',
+ rootScope: 'unknown',
+ },
+ msg: '[receive] action=url-parse',
+ });
+ expect(warnLog).toContainEqual({
+ obj: {
+ source: 'custom-scheme',
+ result: 'invalid',
+ codecVersion: 'unknown',
+ targetKind: 'unknown',
+ rootScope: 'unknown',
+ },
+ msg: '[receive] action=url-parse',
+ });
+ });
+
+ test('logs a bounded v2 success classification without token, URL, or target path', async () => {
+ const env = makeEnv();
+ env.readyWindow = { id: 'ready' };
+ const warnLog: Array<{ obj: object; msg: string }> = [];
+ const infoLog: Array<{ obj: object; msg: string }> = [];
+ const fixtureEntry = shareFixture.validShares.find(
+ (entry) => entry.id === 'v2-one-segment-document',
+ );
+ if (!fixtureEntry || fixtureEntry.version !== 2) throw new Error('missing v2 fixture');
+
+ registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ resolveShareTarget: async () => ({ kind: 'miss' }),
+ routeShareToNavigator: () => {},
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ log: {
+ warn: (obj, msg) => warnLog.push({ obj, msg }),
+ info: (obj, msg) => infoLog.push({ obj, msg }),
+ },
+ });
+ env.app.resolveReady();
+ await flushPromises();
+
+ env.app.fireOpenUrl(`https://openknowledge.ai/d/${fixtureEntry.token}`);
+ await flushPromises();
+
+ // A successful parse logs at info, off the warn channel operators alert on.
+ expect(infoLog).toContainEqual({
+ obj: {
+ source: 'universal-link',
+ result: 'ok',
+ codecVersion: 'v2',
+ targetKind: 'doc',
+ rootScope: 'nested',
+ },
+ msg: '[receive] action=url-parse',
+ });
+ const serialized = JSON.stringify([...warnLog, ...infoLog]);
+ expect(serialized).not.toContain(fixtureEntry.token);
+ expect(serialized).not.toContain(fixtureEntry.sharedUrl);
+ expect(serialized).not.toContain(fixtureEntry.target.docPath);
});
test('ok share with no resolveShareTarget dep surfaces warn + no dispatch', async () => {
@@ -1173,11 +1318,13 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
function expectedSharePayload(): ShareUrlPayload {
return {
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/docs/getting-started.md',
+ repositoryTarget: { kind: 'doc', docPath: 'docs/getting-started.md' },
target: { kind: 'doc', docPath: 'docs/getting-started.md' },
};
}
@@ -1240,7 +1387,11 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
expect(resolveShareTarget).toHaveBeenCalledTimes(1);
expect(resolveShareTarget).toHaveBeenCalledWith(expectedSharePayload());
expect(env.openProject).toHaveBeenCalledWith('/Users/me/playbooks', {
- pendingDeepLinkTarget: { kind: 'doc', path: 'docs/getting-started.md' },
+ pendingDeepLinkTarget: {
+ kind: 'doc',
+ path: 'docs/getting-started.md',
+ repositoryPath: 'docs/getting-started.md',
+ },
pendingBranch: 'main',
pendingMultiCandidate: true,
});
@@ -1249,6 +1400,52 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
expect(sendShareDeepLink).not.toHaveBeenCalled();
});
+ test('v2 probes the repository coordinate but navigates the content coordinate', async () => {
+ const env = makeEnv();
+ env.readyWindow = { id: 'pre-existing' };
+ const resolveShareTarget = vi.fn(
+ async (): Promise<CandidateSelection> => ({
+ kind: 'branch-match-ok',
+ candidate: makeCandidate({ path: '/Users/me/playbooks', currentBranch: 'main' }),
+ multiCandidate: false,
+ }),
+ );
+ const checkShareTargetExists = vi.fn(() => 'exists' as const);
+ const sharedUrl = 'https://github.com/inkeep/playbooks/blob/main/wiki/docs/getting-started.md';
+
+ registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ resolveShareTarget,
+ checkShareTargetExists,
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ });
+ env.app.resolveReady();
+ await flushPromises();
+ env.app.fireOpenUrl(`https://openknowledge.ai/d/${encodeShareUrl(sharedUrl, 1)}`);
+ await flushPromises();
+ await flushPromises();
+
+ expect(checkShareTargetExists).toHaveBeenCalledWith(
+ '/Users/me/playbooks',
+ 'doc',
+ 'wiki/docs/getting-started.md',
+ );
+ expect(env.openProject).toHaveBeenCalledWith('/Users/me/playbooks', {
+ pendingDeepLinkTarget: {
+ kind: 'doc',
+ path: 'docs/getting-started.md',
+ repositoryPath: 'wiki/docs/getting-started.md',
+ contentRootDepth: 1,
+ },
+ pendingBranch: 'main',
+ pendingMultiCandidate: false,
+ });
+ });
+
test('branch-match-ok with multiCandidate=false omits the toast hint', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
@@ -1278,7 +1475,11 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
await flushPromises();
expect(env.openProject).toHaveBeenCalledWith('/Users/me/solo-clone', {
- pendingDeepLinkTarget: { kind: 'doc', path: 'docs/getting-started.md' },
+ pendingDeepLinkTarget: {
+ kind: 'doc',
+ path: 'docs/getting-started.md',
+ repositoryPath: 'docs/getting-started.md',
+ },
pendingBranch: 'main',
pendingMultiCandidate: false,
});
@@ -1323,6 +1524,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
kind: 'doc',
branch: 'main',
multiCandidate: true,
+ repositoryPath: 'docs/getting-started.md',
});
// Must NOT re-spawn through openProject on the warm path.
expect(env.openProject).not.toHaveBeenCalled();
@@ -1933,11 +2135,15 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// Each dispatched to its own project + its own doc — no stale overwrite.
expect(env.openProject).toHaveBeenCalledWith(
'/p/repo-b',
- expect.objectContaining({ pendingDeepLinkTarget: { kind: 'doc', path: 'b.md' } }),
+ expect.objectContaining({
+ pendingDeepLinkTarget: { kind: 'doc', path: 'b.md', repositoryPath: 'b.md' },
+ }),
);
expect(env.openProject).toHaveBeenCalledWith(
'/p/repo-a',
- expect.objectContaining({ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md' } }),
+ expect.objectContaining({
+ pendingDeepLinkTarget: { kind: 'doc', path: 'a.md', repositoryPath: 'a.md' },
+ }),
);
});
});
@@ -2138,10 +2344,12 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
// The Handoff Universal Link is parsed and reaches main-side resolution.
expect(resolveShareTarget).toHaveBeenCalledTimes(1);
expect(resolveShareTarget).toHaveBeenCalledWith({
+ contentRootDepth: null,
host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
+ repositoryTarget: { kind: 'doc', docPath: 'x.md' },
sharedUrl: 'https://github.com/inkeep/playbooks/blob/main/x.md',
target: { kind: 'doc', docPath: 'x.md' },
});
diff --git a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
index 7aaa25a49..0e14a8c17 100644
--- a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
+++ b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts
@@ -31,12 +31,12 @@
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { _electron as electron } from '@playwright/test';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
-import { expect, test } from './_helpers/smoke-test';
+import { expect, type SmokeFixtures, test } from './_helpers/smoke-test';
const TARGET = resolveDesktopTarget();
@@ -51,7 +51,63 @@ function git(cwd: string, ...args: string[]): void {
});
}
-const OK_CONFIG = "content:\n dir: '.'\n include: ['**/*.md']\n exclude: []\n";
+const ROOT_OK_CONFIG = "content:\n dir: '.'\n include: ['**/*.md']\n exclude: []\n";
+const NESTED_OK_CONFIG = "content:\n dir: wiki\n include: ['**/*.md']\n exclude: []\n";
+const shareFixture: unknown = JSON.parse(
+ readFileSync(
+ new URL('../../../../test-support/fixtures/share-url-v1-v2.json', import.meta.url),
+ 'utf8',
+ ),
+);
+const v2Share =
+ typeof shareFixture === 'object' &&
+ shareFixture !== null &&
+ 'validShares' in shareFixture &&
+ Array.isArray(shareFixture.validShares)
+ ? shareFixture.validShares.find(
+ (share) =>
+ typeof share === 'object' &&
+ share !== null &&
+ 'id' in share &&
+ share.id === 'v2-one-segment-document',
+ )
+ : undefined;
+if (
+ typeof v2Share !== 'object' ||
+ v2Share === null ||
+ !('version' in v2Share) ||
+ v2Share.version !== 2 ||
+ !('token' in v2Share) ||
+ typeof v2Share.token !== 'string'
+) {
+ throw new Error('canonical v2 nested-document fixture is missing');
+}
+const V2_SHARE_TOKEN = v2Share.token;
+const maxV2Share =
+ typeof shareFixture === 'object' &&
+ shareFixture !== null &&
+ 'bounds' in shareFixture &&
+ typeof shareFixture.bounds === 'object' &&
+ shareFixture.bounds !== null &&
+ 'maxCase' in shareFixture.bounds
+ ? shareFixture.bounds.maxCase
+ : undefined;
+if (
+ typeof maxV2Share !== 'object' ||
+ maxV2Share === null ||
+ !('token' in maxV2Share) ||
+ typeof maxV2Share.token !== 'string' ||
+ !('target' in maxV2Share) ||
+ typeof maxV2Share.target !== 'object' ||
+ maxV2Share.target === null ||
+ !('docPath' in maxV2Share.target) ||
+ typeof maxV2Share.target.docPath !== 'string'
+) {
+ throw new Error('canonical maximum v2 fixture is missing');
+}
+const MAX_V2_SHARE_TOKEN = maxV2Share.token;
+const MAX_V2_SHARE_TARGET_PATH = maxV2Share.target.docPath;
+const MAX_V2_CUSTOM_URI = `openknowledge://share?token=${MAX_V2_SHARE_TOKEN}`;
interface MissFixture {
readonly root: string;
@@ -59,6 +115,12 @@ interface MissFixture {
readonly docPath: string;
}
+interface MissFixtureOptions {
+ readonly docPath?: string;
+ readonly okConfig?: string;
+ readonly extraFiles?: Readonly<Record<string, string>>;
+}
+
/**
* Build origin (bare) + receiver (clone) where the shared doc was committed then
* deleted on the branch, so the receiver's working tree lacks it and origin's
@@ -66,9 +128,9 @@ interface MissFixture {
* matches the dispatched window's `projectPath` after the macOS `/var` ->
* `/private/var` normalization the main process applies.
*/
-function setupDeletedTargetFixture(): MissFixture {
+function setupDeletedTargetFixture(options: MissFixtureOptions = {}): MissFixture {
const uniq = randomUUID().slice(0, 8);
- const docPath = `docs/moved-${uniq}.md`;
+ const docPath = options.docPath ?? `docs/moved-${uniq}.md`;
const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-share-miss-')));
const originDir = join(root, 'origin.git');
const seedDir = join(root, 'seed');
@@ -83,9 +145,13 @@ function setupDeletedTargetFixture(): MissFixture {
git(seedDir, 'config', 'user.name', 'Test');
git(seedDir, 'remote', 'add', 'origin', originDir);
mkdirSync(join(seedDir, '.ok'), { recursive: true });
- writeFileSync(join(seedDir, '.ok', 'config.yml'), OK_CONFIG);
- mkdirSync(join(seedDir, 'docs'), { recursive: true });
+ writeFileSync(join(seedDir, '.ok', 'config.yml'), options.okConfig ?? ROOT_OK_CONFIG);
+ mkdirSync(dirname(join(seedDir, docPath)), { recursive: true });
writeFileSync(join(seedDir, docPath), `# moved ${uniq}\n`);
+ for (const [path, content] of Object.entries(options.extraFiles ?? {})) {
+ mkdirSync(dirname(join(seedDir, path)), { recursive: true });
+ writeFileSync(join(seedDir, path), content);
+ }
git(seedDir, 'add', '.');
git(seedDir, 'commit', '-m', 'seed doc');
git(seedDir, 'push', 'origin', 'main');
@@ -97,6 +163,82 @@ function setupDeletedTargetFixture(): MissFixture {
return { root, receiver: realpathSync(receiverDir), docPath };
}
+type MissState = {
+ phase: string | null;
+ verdict: string | null;
+ hasEditor: boolean;
+ bodyText: string;
+};
+
+async function expectDeletedTargetMiss(
+ fixture: MissFixture,
+ shareUrl: string,
+ captureStderrFor: SmokeFixtures['captureStderrFor'],
+): Promise<void> {
+ const tmpHome = mkdtempSync(join(tmpdir(), 'ok-share-miss-home-'));
+ const userData = join(tmpHome, 'electron-userdata');
+ mkdirSync(userData, { recursive: true });
+ writeFileSync(
+ join(userData, 'state.json'),
+ JSON.stringify({
+ recentProjects: [
+ {
+ path: fixture.receiver,
+ name: 'receiver',
+ lastOpenedAt: new Date().toISOString(),
+ gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git',
+ },
+ ],
+ projectSessions: {},
+ }),
+ );
+
+ const app = await electron.launch(
+ desktopLaunchOptions({
+ target: TARGET,
+ args: [`--user-data-dir=${userData}`, shareUrl],
+ timeout: 30_000,
+ }),
+ );
+ captureStderrFor(app, { cleanupDirs: [fixture.root, tmpHome] });
+
+ const firstWindow = await app.firstWindow({ timeout: 15_000 });
+ expect(firstWindow).toBeDefined();
+
+ // Poll every window until one resolves the miss DIALOG. A known-missing
+ // target shows the honest verdict as a modal WITHOUT navigating to the dead
+ // path, so `hasEditor === false` alongside the resolved dialog is the "never
+ // create-mode fork" proof — the receiver never landed in an editor at the
+ // shared path.
+ let resolved: MissState | null = null;
+ await expect(async () => {
+ for (const page of app.windows()) {
+ const info: MissState | null = await page
+ .evaluate(() => {
+ const dialog = document.querySelector('[data-testid="share-receive-miss-dialog"]');
+ return {
+ phase: dialog?.getAttribute('data-phase') ?? null,
+ verdict: dialog?.getAttribute('data-verdict') ?? null,
+ hasEditor: !!document.querySelector('.ProseMirror'),
+ bodyText: document.body?.innerText ?? '',
+ };
+ })
+ .catch(() => null);
+ if (info?.phase === 'resolved') {
+ resolved = info;
+ return;
+ }
+ }
+ throw new Error('no window has resolved the share-receive miss dialog yet');
+ }).toPass({ timeout: 60_000 });
+
+ if (resolved === null) throw new Error('share-receive miss dialog never resolved');
+ const outcome: MissState = resolved;
+ expect(outcome.verdict).toBe('deleted');
+ expect(outcome.hasEditor).toBe(false);
+ expect(outcome.bodyText).toContain('removed from branch');
+}
+
test.describe('share-receive miss terminal smoke', () => {
test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
test.skip(!DARWIN, 'Deep-link URL scheme is macOS-only in v0.');
@@ -107,77 +249,74 @@ test.describe('share-receive miss terminal smoke', () => {
}, testInfo) => {
testInfo.setTimeout(120_000);
const fixture = setupDeletedTargetFixture();
+ const githubBlobUrl = `https://github.com/inkeep/open-knowledge/blob/main/${fixture.docPath}`;
+ await expectDeletedTargetMiss(
+ fixture,
+ `openknowledge://share?url=${encodeURIComponent(githubBlobUrl)}`,
+ captureStderrFor,
+ );
+ });
- const tmpHome = mkdtempSync(join(tmpdir(), 'ok-share-miss-home-'));
+ test('an exact canonical v2 nested-content argv handoff lands a deleted target on the miss dialog', async ({
+ captureStderrFor,
+ }, testInfo) => {
+ testInfo.setTimeout(120_000);
+ const fixture = setupDeletedTargetFixture({
+ docPath: 'wiki/modules/backend-libraries.md',
+ okConfig: NESTED_OK_CONFIG,
+ extraFiles: { 'wiki/keep.md': '# keep content root present\n' },
+ });
+ await expectDeletedTargetMiss(
+ fixture,
+ `openknowledge://share?token=${V2_SHARE_TOKEN}`,
+ captureStderrFor,
+ );
+ });
+
+ test('the exact 4,012-character canonical v2 custom URI survives argv delivery unchanged', async ({
+ captureStderrFor,
+ }, testInfo) => {
+ testInfo.setTimeout(120_000);
+ expect(MAX_V2_SHARE_TOKEN).toHaveLength(3984);
+ expect(MAX_V2_CUSTOM_URI).toHaveLength(4012);
+
+ const tmpHome = mkdtempSync(join(tmpdir(), 'ok-share-max-argv-home-'));
const userData = join(tmpHome, 'electron-userdata');
mkdirSync(userData, { recursive: true });
writeFileSync(
join(userData, 'state.json'),
- JSON.stringify({
- recentProjects: [
- {
- path: fixture.receiver,
- name: 'receiver',
- lastOpenedAt: new Date().toISOString(),
- gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git',
- },
- ],
- projectSessions: {},
- }),
+ JSON.stringify({ recentProjects: [], projectSessions: {} }),
);
- const githubBlobUrl = `https://github.com/inkeep/open-knowledge/blob/main/${fixture.docPath}`;
- const shareUrl = `openknowledge://share?url=${encodeURIComponent(githubBlobUrl)}`;
-
const app = await electron.launch(
desktopLaunchOptions({
target: TARGET,
- args: [`--user-data-dir=${userData}`, shareUrl],
+ args: [`--user-data-dir=${userData}`, MAX_V2_CUSTOM_URI],
timeout: 30_000,
}),
);
- captureStderrFor(app, { cleanupDirs: [fixture.root, tmpHome] });
-
- const firstWindow = await app.firstWindow({ timeout: 15_000 });
- expect(firstWindow).toBeDefined();
-
- // Poll every window until one resolves the miss DIALOG. A known-missing
- // target shows the honest verdict as a modal WITHOUT navigating to the dead
- // path, so `hasEditor === false` alongside the resolved dialog is the "never
- // create-mode fork" proof — the receiver never landed in an editor at the
- // shared path.
- type MissState = {
- phase: string | null;
- verdict: string | null;
- hasEditor: boolean;
- bodyText: string;
- };
- let resolved: MissState | null = null;
+ captureStderrFor(app, { cleanupDirs: [tmpHome] });
+ await app.firstWindow({ timeout: 15_000 });
+
+ let dialogText = '';
await expect(async () => {
for (const page of app.windows()) {
- const info: MissState | null = await page
- .evaluate(() => {
- const dialog = document.querySelector('[data-testid="share-receive-miss-dialog"]');
- return {
- phase: dialog?.getAttribute('data-phase') ?? null,
- verdict: dialog?.getAttribute('data-verdict') ?? null,
- hasEditor: !!document.querySelector('.ProseMirror'),
- bodyText: document.body?.innerText ?? '',
- };
- })
+ const text = await page
+ .evaluate((expectedPath) => {
+ const dialog = document.querySelector('[data-testid="share-receive-dialog"]');
+ const content = dialog?.textContent ?? null;
+ return content?.includes(expectedPath) ? content : null;
+ }, MAX_V2_SHARE_TARGET_PATH)
.catch(() => null);
- if (info?.phase === 'resolved') {
- resolved = info;
+ if (text !== null) {
+ dialogText = text;
return;
}
}
- throw new Error('no window has resolved the share-receive miss dialog yet');
+ throw new Error('maximum v2 argv share has not reached the receiver dialog');
}).toPass({ timeout: 60_000 });
- if (resolved === null) throw new Error('share-receive miss dialog never resolved');
- const outcome: MissState = resolved;
- expect(outcome.verdict).toBe('deleted');
- expect(outcome.hasEditor).toBe(false);
- expect(outcome.bodyText).toContain('removed from branch');
+ expect(dialogText).toContain('o/r');
+ expect(dialogText).toContain(MAX_V2_SHARE_TARGET_PATH);
});
});
diff --git a/packages/server/src/api-extension.branch-info.test.ts b/packages/server/src/api-extension.branch-info.test.ts
index 4ae7506c7..2861dd106 100644
--- a/packages/server/src/api-extension.branch-info.test.ts
+++ b/packages/server/src/api-extension.branch-info.test.ts
@@ -37,11 +37,11 @@ function initRepo(cwd: string): void {
async function bootRig(
initProject: ((projectDir: string) => void) | null,
- options: { withoutProjectDir?: boolean } = {},
+ options: { withoutProjectDir?: boolean; contentDirRelative?: string } = {},
): Promise<TestRig> {
const tmpRoot = mkdtempSync(join(tmpdir(), 'branch-info-'));
const projectDir = join(tmpRoot, 'project');
- const contentDir = join(projectDir, 'content');
+ const contentDir = join(projectDir, options.contentDirRelative ?? '.');
mkdirSync(contentDir, { recursive: true });
initProject?.(projectDir);
@@ -110,6 +110,36 @@ afterEach(async () => {
});
describe('GET /api/git/branch-info', () => {
+ test('probes an explicit v2 repository path without reapplying the receiver content root', async () => {
+ rig = await bootRig(
+ (projectDir) => {
+ initRepo(projectDir);
+ write(projectDir, 'content/docs/guide.md', '# guide\n');
+ commitAll(projectDir, 'init');
+ },
+ { contentDirRelative: 'content' },
+ );
+
+ const res = await getBranchInfo(rig.port, 'main', 'content/docs/guide.md');
+ expect(res.status).toBe(200);
+ expect((await res.json()).shareTargetExists).toBe(true);
+ });
+
+ test('keeps a nested-root v1 folder path repository-relative without wiki/wiki', async () => {
+ rig = await bootRig(
+ (projectDir) => {
+ initRepo(projectDir);
+ write(projectDir, 'wiki/guide.md', '# guide\n');
+ commitAll(projectDir, 'init');
+ },
+ { contentDirRelative: 'wiki' },
+ );
+
+ const res = await getBranchInfo(rig.port, 'main', 'wiki', 'folder');
+ expect(res.status).toBe(200);
+ expect((await res.json()).shareTargetExists).toBe(true);
+ });
+
test('clean tree with file present on share branch and current branch matches', async () => {
rig = await bootRig((projectDir) => {
initRepo(projectDir);
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index bdecbda17..7ac08e83f 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -19956,14 +19956,14 @@ export function createApiExtension(
if (contentRel === null) {
throw new Error('content dir is not contained within the project dir');
}
- // Known limitation: when `content.dir !== '.'`, a NON-root doc/folder
- // share URL omits the content.dir prefix, so the raw github.com link
- // points one level too shallow. A correct fix needs receiver-side
- // content.dir resolution — the in-app receive nav is content-relative
- // and lands correctly, so prefixing the URL here would double-count
- // against it. Until that lands, warn so the mis-point is discoverable
- // in ops rather than silent. The dominant `content.dir === '.'` case
- // (contentRel === '') is fully correct.
+ // A non-root content.dir link keeps its historical shallow source URL:
+ // the content-relative target is NOT prefixed with content.dir. Older
+ // installed apps treat a received URL as the content-relative path
+ // directly, and in-app receive navigation is already content-relative and
+ // lands correctly — so prefixing content.dir into the source here would
+ // double-count against the receiver. The tradeoff is that the raw
+ // github.com link may point one level too shallow; warn so that mis-point
+ // is observable in ops rather than silent.
const sharingNonRootTarget =
body.kind === 'doc' ? body.docPath !== '' : body.folderPath !== '';
if (contentRel !== '' && sharingNonRootTarget) {
@@ -20085,6 +20085,9 @@ export function createApiExtension(
);
return;
}
+ // The desktop sends the URL-derived repository coordinate explicitly.
+ // V1 has no mount metadata and must never be re-rooted from receiver
+ // config; v2 already projected its separate content target at decode.
const info = await computeBranchInfo(projectDir, branch, path, kind);
successResponse(res, 200, BranchInfoResponseSchema, info, {
handler: BRANCH_INFO_HANDLER_TAG,
@@ -20117,6 +20120,22 @@ export function createApiExtension(
* Updates only remote-tracking refs, no CRDT mutation — so the
* attribution-sweep meta-test exempts it (see EXEMPT_HANDLERS).
*/
+ function projectRenamedShareTarget(
+ repositoryPath: string,
+ renamedRepositoryPath: string,
+ contentRootDepth: number,
+ ): { verdict: 'renamed'; renamedTo: string } | { verdict: 'unknown' } {
+ const originalSegments = repositoryPath.split('/');
+ const renamedSegments = renamedRepositoryPath.split('/');
+ if (contentRootDepth >= originalSegments.length || contentRootDepth >= renamedSegments.length) {
+ return { verdict: 'unknown' };
+ }
+ for (let index = 0; index < contentRootDepth; index += 1) {
+ if (originalSegments[index] !== renamedSegments[index]) return { verdict: 'unknown' };
+ }
+ return { verdict: 'renamed', renamedTo: renamedSegments.slice(contentRootDepth).join('/') };
+ }
+
const handleShareTargetStatus = withValidation(
ShareTargetStatusRequestSchema,
async (_req, res, body) => {
@@ -20144,21 +20163,17 @@ export function createApiExtension(
});
return;
}
- // The target lives under content.dir; map the content-relative request
- // path to the repo-relative path git reads (same join as construct-url;
- // '' for the dominant content.dir === '.' case).
- const contentRel = toGitRelativePath(projectDir, contentDir);
- if (contentRel === null) {
- throw new Error('content dir is not contained within the project dir');
- }
- const gitPath =
- contentRel === ''
- ? body.path
- : body.path === ''
- ? contentRel
- : `${contentRel}/${body.path}`;
- const status = await computeShareTargetStatus(projectDir, body.branch, gitPath, body.kind);
- successResponse(res, 200, ShareTargetStatusResponseSchema, status, {
+ const status = await computeShareTargetStatus(
+ projectDir,
+ body.branch,
+ body.path,
+ body.kind,
+ );
+ const contentStatus =
+ status.verdict !== 'renamed' || body.contentRootDepth === undefined
+ ? status
+ : projectRenamedShareTarget(body.path, status.renamedTo, body.contentRootDepth);
+ successResponse(res, 200, ShareTargetStatusResponseSchema, contentStatus, {
handler: SHARE_TARGET_STATUS_HANDLER_TAG,
});
} catch (err) {
diff --git a/packages/server/src/share/endpoint-real-git.test.ts b/packages/server/src/share/endpoint-real-git.test.ts
index 5432df0ca..2cb2f3883 100644
--- a/packages/server/src/share/endpoint-real-git.test.ts
+++ b/packages/server/src/share/endpoint-real-git.test.ts
@@ -103,6 +103,41 @@ describe('POST /api/share/target-status (fetch through the endpoint)', () => {
expect(await res.json()).toEqual({ verdict: 'renamed', renamedTo: 'new.md' });
});
+ test('a v2 rename under a nested content root returns a content-relative destination', async () => {
+ const t = newTriangle();
+ t.seedAndPush('wiki/old.md', '# stable content that survives the move intact\n');
+ const receiver = t.cloneReceiver();
+ t.renameOnOrigin('wiki/old.md', 'wiki/new.md');
+
+ rig = await bootEndpointServer({ projectDir: receiver, contentDir: `${receiver}/wiki` });
+ const res = await postTargetStatus(rig.port, {
+ branch: t.branch,
+ path: 'wiki/old.md',
+ kind: 'doc',
+ contentRootDepth: 1,
+ });
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ verdict: 'renamed', renamedTo: 'new.md' });
+ });
+
+ test('a nested-root v1 rename stays repository-relative without wiki/wiki', async () => {
+ const t = newTriangle();
+ t.seedAndPush('wiki/old.md', '# stable content that survives the move intact\n');
+ const receiver = t.cloneReceiver();
+ t.renameOnOrigin('wiki/old.md', 'wiki/new.md');
+
+ rig = await bootEndpointServer({ projectDir: receiver, contentDir: `${receiver}/wiki` });
+ const res = await postTargetStatus(rig.port, {
+ branch: t.branch,
+ path: 'wiki/old.md',
+ kind: 'doc',
+ });
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ verdict: 'renamed', renamedTo: 'wiki/new.md' });
+ });
+
test('an unreachable origin degrades to unknown (fail-open through the endpoint)', async () => {
const t = newTriangle();
t.seedAndPush('doc.md', 'one\n');
diff --git a/test-support/fixtures/share-url-v1-v2.json b/test-support/fixtures/share-url-v1-v2.json
new file mode 100644
index 000000000..c21a12b6d
--- /dev/null
+++ b/test-support/fixtures/share-url-v1-v2.json
@@ -0,0 +1,431 @@
+{
+ "schemaVersion": 1,
+ "bounds": {
+ "maxV2TokenChars": 3984,
+ "maxV2PayloadBytes": 2988,
+ "maxV2SharedUrlUtf8Bytes": 2985,
+ "maxV2CustomUriChars": 4012,
+ "maxDeferredCookieBytes": 4096,
+ "maxCase": {
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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 {
+ "id": "v1-folder",
+ "version": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/tree/main/docs/guides",
+ "target": {
+ "kind": "folder",
+ "folderPath": "docs/guides"
+ },
+ "token": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvdHJlZS9tYWluL2RvY3MvZ3VpZGVz"
+ },
+ {
+ "id": "v1-repository-root",
+ "version": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/tree/main",
+ "target": {
+ "kind": "folder",
+ "folderPath": ""
+ },
+ "token": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvdHJlZS9tYWlu"
+ },
+ {
+ "id": "v2-one-segment-document",
+ "version": 2,
+ "contentRootDepth": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/wiki/modules/backend-libraries.md",
+ "target": {
+ "kind": "doc",
+ "docPath": "modules/backend-libraries.md"
+ },
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vd2lraS9tb2R1bGVzL2JhY2tlbmQtbGlicmFyaWVzLm1k"
+ },
+ {
+ "id": "v2-one-segment-folder",
+ "version": 2,
+ "contentRootDepth": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/tree/main/wiki/modules",
+ "target": {
+ "kind": "folder",
+ "folderPath": "modules"
+ },
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS90cmVlL21haW4vd2lraS9tb2R1bGVz"
+ },
+ {
+ "id": "v2-one-segment-content-root",
+ "version": 2,
+ "contentRootDepth": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/tree/main/wiki",
+ "target": {
+ "kind": "folder",
+ "folderPath": ""
+ },
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS90cmVlL21haW4vd2lraQ"
+ },
+ {
+ "id": "v2-two-segment-document",
+ "version": 2,
+ "contentRootDepth": 2,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/docs/wiki/guide.md",
+ "target": {
+ "kind": "doc",
+ "docPath": "guide.md"
+ },
+ "token": "AgACaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vZG9jcy93aWtpL2d1aWRlLm1k"
+ },
+ {
+ "id": "v2-unicode-root",
+ "version": 2,
+ "contentRootDepth": 2,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/%E7%9F%A5%E8%AD%98/%E8%B3%87%E6%96%99/%E6%A1%88%E5%85%A7.md",
+ "target": {
+ "kind": "doc",
+ "docPath": "案內.md"
+ },
+ "token": "AgACaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vJUU3JTlGJUE1JUU4JUFEJTk4LyVFOCVCMyU4NyVFNiU5NiU5OS8lRTYlQTElODglRTUlODUlQTcubWQ"
+ },
+ {
+ "id": "v2-slashed-branch",
+ "version": 2,
+ "contentRootDepth": 1,
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/feat%2Fshare-v2/wiki/a.md",
+ "target": {
+ "kind": "doc",
+ "docPath": "a.md"
+ },
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL2ZlYXQlMkZzaGFyZS12Mi93aWtpL2EubWQ"
+ },
+ {
+ "id": "v2-ghes-root-path",
+ "version": 2,
+ "contentRootDepth": 1,
+ "sharedUrl": "https://ghes.acme.test/team/notes/blob/main/wiki/a.md",
+ "target": {
+ "kind": "doc",
+ "docPath": "a.md"
+ },
+ "token": "AgABaHR0cHM6Ly9naGVzLmFjbWUudGVzdC90ZWFtL25vdGVzL2Jsb2IvbWFpbi93aWtpL2EubWQ"
+ }
+ ],
+ "legacyAliases": [
+ {
+ "id": "v1-noncanonical-pad-bits",
+ "token": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWR",
+ "canonicalToken": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWQ",
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md"
+ },
+ {
+ "id": "v1-query-suffix",
+ "token": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWQ?utm_source=slack",
+ "canonicalToken": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWQ",
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md"
+ },
+ {
+ "id": "v1-fragment-suffix",
+ "token": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWQ#section",
+ "canonicalToken": "AWh0dHBzOi8vZ2l0aHViLmNvbS9pbmtlZXAvb3Blbi1rbm93bGVkZ2UvYmxvYi9tYWluL2RvY3MvZ3VpZGUubWQ",
+ "sharedUrl": "https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md"
+ }
+ ],
+ "invalidTokens": [
+ {
+ "id": "empty",
+ "token": "",
+ "reason": "empty"
+ },
+ {
+ "id": "invalid-base64",
+ "token": "not!valid!base64",
+ "reason": "base64"
+ },
+ {
+ "id": "v2-truncated-version",
+ "token": "Ag",
+ "reason": "framing"
+ },
+ {
+ "id": "v2-truncated-depth",
+ "token": "AgA",
+ "reason": "framing"
+ },
+ {
+ "id": "v2-missing-url",
+ "token": "AgAB",
+ "reason": "framing"
+ },
+ {
+ "id": "v2-invalid-utf8",
+ "token": "AgABwyg",
+ "reason": "utf8"
+ },
+ {
+ "id": "v2-zero-depth",
+ "token": "AgAAaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hLm1k",
+ "reason": "depth"
+ },
+ {
+ "id": "v2-excess-depth",
+ "token": "AgADaHR0cHM6Ly9naXRodWIuY29tL28vci90cmVlL21haW4vd2lraS9h",
+ "reason": "depth",
+ "sharedUrl": "https://github.com/o/r/tree/main/wiki/a",
+ "contentRootDepth": 3
+ },
+ {
+ "id": "v2-uppercase-host",
+ "token": "AgABaHR0cHM6Ly9HaXRIdWIuY29tL28vci9ibG9iL21haW4vd2lraS9hLm1k",
+ "reason": "canonical-host",
+ "sharedUrl": "https://GitHub.com/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-trailing-host-dot",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tLi9vL3IvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "canonical-host",
+ "sharedUrl": "https://github.com./o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-explicit-port",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tOjQ0My9vL3IvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "authority",
+ "sharedUrl": "https://github.com:443/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-userinfo",
+ "token": "AgABaHR0cHM6Ly94QGdpdGh1Yi5jb20vby9yL2Jsb2IvbWFpbi93aWtpL2EubWQ",
+ "reason": "authority",
+ "sharedUrl": "https://[email protected]/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-query",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hLm1kP3E9MQ",
+ "reason": "query",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a.md?q=1",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-fragment",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hLm1kI3g",
+ "reason": "fragment",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a.md#x",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-http",
+ "token": "AgABaHR0cDovL2dpdGh1Yi5jb20vby9yL2Jsb2IvbWFpbi93aWtpL2EubWQ",
+ "reason": "scheme",
+ "sharedUrl": "http://github.com/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-ghes-path-prefix",
+ "token": "AgABaHR0cHM6Ly9naGVzLmFjbWUudGVzdC9naXQvdGVhbS9ub3Rlcy9ibG9iL21haW4vd2lraS9hLm1k",
+ "reason": "ghes-path-prefix",
+ "sharedUrl": "https://ghes.acme.test/git/team/notes/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-owner-decoded-slash",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28lMkZvL3IvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "owner",
+ "sharedUrl": "https://github.com/o%2Fo/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-owner-encoded-space",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2ElMjBiL3IvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "owner",
+ "sharedUrl": "https://github.com/a%20b/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-repo-encoded-space",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vciUyMHgvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "repo",
+ "sharedUrl": "https://github.com/o/r%20x/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-ip-authority",
+ "token": "AgABaHR0cHM6Ly8xMjcuMC4wLjEvby9yL2Jsb2IvbWFpbi93aWtpL2EubWQ",
+ "reason": "authority",
+ "sharedUrl": "https://127.0.0.1/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-overlong-dns-authority",
+ "token": "AgABaHR0cHM6Ly9hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEuYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiLmNjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjYy5kZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkLmNvbS9vL3IvYmxvYi9tYWluL3dpa2kvYS5tZA",
+ "reason": "authority",
+ "sharedUrl": "https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc.ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd.com/o/r/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-repo-dotgit",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vLmdpdC9ibG9iL21haW4vd2lraS9hLm1k",
+ "reason": "repo",
+ "sharedUrl": "https://github.com/o/.git/blob/main/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-invalid-branch",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL2JhZCUzQXJlZi93aWtpL2EubWQ",
+ "reason": "branch",
+ "sharedUrl": "https://github.com/o/r/blob/bad%3Aref/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-lowercase-percent",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL2ZlYXQlMmZzaGFyZS93aWtpL2EubWQ",
+ "reason": "canonical-percent",
+ "sharedUrl": "https://github.com/o/r/blob/feat%2fshare/wiki/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-decoded-slash",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hJTJGYi5tZA",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a%2Fb.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-backslash",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hJTVDYi5tZA",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a%5Cb.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-raw-dot",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS8uL2EubWQ",
+ "reason": "pre-normalization",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/./a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-encoded-dotdot",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS8lMkUlMkUvYS5tZA",
+ "reason": "pre-normalization",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/%2E%2E/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-dotgit",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS8uZ2l0L2EubWQ",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/.git/a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-nul",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hJTAwYi5tZA",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a%00b.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-target-del",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hJTdGYi5tZA",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a%7Fb.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-malformed-percent",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS9hJVpaLm1k",
+ "reason": "percent",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki/a%ZZ.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-empty-segment",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraS8vYS5tZA",
+ "reason": "target",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki//a.md",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-tree-trailing-slash",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci90cmVlL21haW4vd2lraS8",
+ "reason": "tree-root",
+ "sharedUrl": "https://github.com/o/r/tree/main/wiki/",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-blob-empty-after-projection",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL28vci9ibG9iL21haW4vd2lraQ",
+ "reason": "target-kind",
+ "sharedUrl": "https://github.com/o/r/blob/main/wiki",
+ "contentRootDepth": 1
+ },
+ {
+ "id": "v2-noncanonical-base64-alias",
+ "token": "AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS90cmVlL21haW4vd2lraR",
+ "reason": "canonical-base64"
+ }
+ ],
+ "unsupportedTokens": [
+ {
+ "id": "future-v3",
+ "token": "AwABAg",
+ "version": 3
+ }
+ ],
+ "customSchemeCases": [
+ {
+ "id": "v2-token-only",
+ "uri": "openknowledge://share?token=AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vd2lraS9tb2R1bGVzL2JhY2tlbmQtbGlicmFyaWVzLm1k",
+ "baseline": "invalid",
+ "updated": "ok"
+ },
+ {
+ "id": "v2-token-plus-url",
+ "uri": "openknowledge://share?token=AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vd2lraS9tb2R1bGVzL2JhY2tlbmQtbGlicmFyaWVzLm1k&url=https%3A%2F%2Fgithub.com%2Finkeep%2Fopen-knowledge%2Fblob%2Fmain%2Fwiki%2Fmodules%2Fbackend-libraries.md",
+ "baseline": "ok-v1-url",
+ "updated": "invalid"
+ },
+ {
+ "id": "v2-duplicate-token",
+ "uri": "openknowledge://share?token=AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS9ibG9iL21haW4vd2lraS9tb2R1bGVzL2JhY2tlbmQtbGlicmFyaWVzLm1k&token=AgABaHR0cHM6Ly9naXRodWIuY29tL2lua2VlcC9vcGVuLWtub3dsZWRnZS90cmVlL21haW4vd2lraS9tb2R1bGVz",
+ "baseline": "invalid",
+ "updated": "invalid"
+ },
+ {
+ "id": "v2-empty-token",
+ "uri": "openknowledge://share?token=",
+ "baseline": "invalid",
+ "updated": "invalid"
+ },
+ {
+ "id": "future-token-only",
+ "uri": "openknowledge://share?token=AwABAg",
+ "baseline": "invalid",
+ "updated": "unsupported-version"
+ },
+ {
+ "id": "historical-v1-url",
+ "uri": "openknowledge://share?url=https%3A%2F%2Fgithub.com%2Finkeep%2Fopen-knowledge%2Fblob%2Fmain%2Fdocs%2Fguide.md",
+ "baseline": "ok-v1-url",
+ "updated": "ok-v1-url"
+ }
+ ]
+}
diff --git a/test-support/share/frozen-v1-share-reader.test-helper.ts b/test-support/share/frozen-v1-share-reader.test-helper.ts
new file mode 100644
index 000000000..38ec0ec06
--- /dev/null
+++ b/test-support/share/frozen-v1-share-reader.test-helper.ts
@@ -0,0 +1,74 @@
+export type FrozenV1TokenOutcome =
+ | { readonly kind: 'ok'; readonly version: 1; readonly sharedUrl: string }
+ | { readonly kind: 'invalid' }
+ | { readonly kind: 'unsupported-version'; readonly version: number };
+
+export type FrozenV1CustomOutcome = 'invalid' | 'ok-v1-url';
+
+/**
+ * Release-baseline v1 decoder copied before v2 exists. It deliberately owns
+ * its base64url and UTF-8 paths and must never import the production codec.
+ */
+export function frozenV1DecodeShareToken(encoded: string): FrozenV1TokenOutcome {
+ const cleaned = encoded.split(/[?#]/)[0];
+ if (cleaned.length === 0) return { kind: 'invalid' };
+
+ let bytes: Uint8Array;
+ try {
+ bytes = frozenBase64UrlDecode(cleaned);
+ } catch {
+ return { kind: 'invalid' };
+ }
+ if (bytes.length === 0) return { kind: 'invalid' };
+
+ const version = bytes[0];
+ if (version !== 0x01) return { kind: 'unsupported-version', version };
+
+ try {
+ const sharedUrl = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(1));
+ return { kind: 'ok', version: 1, sharedUrl };
+ } catch {
+ return { kind: 'invalid' };
+ }
+}
+
+/**
+ * Release-baseline custom-scheme routing ignores unknown query parameters and
+ * reads only the historical url field. Token-only input is therefore invalid.
+ */
+export function frozenV1CustomSchemeOutcome(input: string): FrozenV1CustomOutcome {
+ let parsed: URL;
+ try {
+ parsed = new URL(input);
+ } catch {
+ return 'invalid';
+ }
+ if (parsed.protocol !== 'openknowledge:' || parsed.hostname !== 'share') return 'invalid';
+
+ const sharedUrl = parsed.searchParams.get('url');
+ if (!sharedUrl || sharedUrl.length > 4096 || sharedUrl.includes('\0')) return 'invalid';
+
+ let source: URL;
+ try {
+ source = new URL(sharedUrl);
+ } catch {
+ return 'invalid';
+ }
+ if (source.protocol !== 'https:' || source.username || source.password) return 'invalid';
+
+ const segments = source.pathname.split('/').filter(Boolean);
+ const kindIndex = segments.findIndex((segment) => segment === 'blob' || segment === 'tree');
+ if (kindIndex !== 2 || segments[kindIndex + 1] === undefined) return 'invalid';
+ if (segments[kindIndex] === 'blob' && segments[kindIndex + 2] === undefined) return 'invalid';
+ return 'ok-v1-url';
+}
+
+function frozenBase64UrlDecode(input: string): Uint8Array {
+ if (!/^[A-Za-z0-9_-]*$/.test(input)) {
+ throw new Error('non-base64url input');
+ }
+ const base64 = input.replace(/-/g, '+').replace(/_/g, '/');
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
+ const binary = atob(padded);
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
+}
diff --git a/turbo.json b/turbo.json
index 5e1348237..0e6d8e6c3 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,5 +1,6 @@
{
"$schema": "https://turbo.build/schema.json",
+ "globalDependencies": ["test-support/fixtures/share-url-v1-v2.json"],
"tasks": {
"build": {
"dependsOn": ["^build"],
@@ -35,7 +36,8 @@
},
"@inkeep/open-knowledge-docs#build": {
"dependsOn": ["^build", "typecheck"],
- "outputs": ["dist/**", ".next/**"]
+ "outputs": ["dist/**", ".next/**"],
+ "env": ["VERCEL_GIT_COMMIT_SHA", "GITHUB_SHA"]
},
"test": {
"dependsOn": ["^build"],