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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -1666,7 +1666,10 @@ arrive in the query, in a `url` parameter, or in the fragment, which a page on t
and returns once in the query. The id is exchanged for the person's login token, used only in
the main process to list projects and datasets and to create a project key with the Editor
role, then logged out. Only the key is kept. The sign-in page must be on `https://www.sanity.io`.
A suggestion comes from the site's `.env` (`*SANITY_PROJECT_ID`, `*SANITY_DATASET`). Sessions
A suggestion comes from the site's `.env` (`*SANITY_PROJECT_ID`, `*SANITY_DATASET`); when that
names none of the person's projects, from a `projectId: '…'` string literal in the site's `astro.config.*`,
`sanity.config.*` or `sanity.cli.*`, at the root or in `studio/`, read without running them.
Only a project the person belongs to is suggested. Sessions
time out after five minutes. A role that cannot create keys is told to paste an Editor key instead.

While Stacki previews a project with a Sanity connection, its dev server gets
Expand Down
15 changes: 9 additions & 6 deletions electron/content/sanityLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
// sign-in page with that server as the place to come back to.
// 2. Sanity redirects back with a one-time session id, exchanged for the
// person's login token.
// 3. Their projects and datasets are listed; the one the site's own .env
// names is suggested.
// 3. Their projects and datasets are listed; the one the site's own .env or
// config files name is suggested.
// 4. On their choice, a project key with the Editor role is created and kept
// (encrypted, cmsConnectionStore.ts), and the login token is logged out.
//
Expand All @@ -25,6 +25,7 @@ import { described, type Described } from '../../shared/properties/i18n/messageR
import { SANITY_LOGIN_TIMEOUT_MS, type SanityLoginRequest, type SanityLoginState, type SanityProjectChoice } from '../../shared/properties/cmsConnections';
import type { CmsConnectionStore } from './cmsConnectionStore';
import { SanityRequestError, createSanityEditorKey, sanityLoginURL, sanityLogout, sanityProjects, sanityTokenForSession } from './sanityApi';
import { siteConfigProjectIds } from './sanityProjectSource';

const SUCCESS_PAGE = 'https://www.sanity.io/login/success';
// The .env lines read for a suggestion, and the longest file read for them.
Expand Down Expand Up @@ -266,8 +267,9 @@ function failureProblem(error: unknown): Described {
return message.length > 0 ? { message: message.slice(0, 900) } : described('cmsBackend.sanity.signInFailed');
}

// The project and dataset the site itself reads, from its .env files, when one
// of the person's projects has them.
// The project and dataset the site itself reads, when one of the person's
// projects has them: the project from its .env files, else from a `projectId`
// its config files write (sanityProjectSource.ts); the dataset from .env.
function siteSuggestion(projectRoot: string, projects: readonly SanityProjectChoice[]) {
const values = new Map<string, string>();
for (const name of ENV_FILES) {
Expand All @@ -276,9 +278,10 @@ function siteSuggestion(projectRoot: string, projects: readonly SanityProjectCho
}
}
const pick = (suffix: string) => [...values].find(([key]) => /^(PUBLIC_|SANITY_STUDIO_|NEXT_PUBLIC_)?SANITY_/.test(key) && key.endsWith(suffix))?.[1];
const projectId = pick('PROJECT_ID');
const envProjectId = pick('PROJECT_ID');
const candidates = envProjectId === undefined ? siteConfigProjectIds(projectRoot) : [envProjectId, ...siteConfigProjectIds(projectRoot)];
const dataset = pick('DATASET') ?? 'production';
const project = projects.find((entry) => entry.id === projectId);
const project = candidates.map((id) => projects.find((entry) => entry.id === id)).find((entry) => entry !== undefined);
return project && project.datasets.includes(dataset) ? { projectId: project.id, dataset } : undefined;
}

Expand Down
80 changes: 80 additions & 0 deletions electron/content/sanityProjectSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// The Sanity project a site names in its own config files, read without running
// them: a site often writes `projectId: '…'` in astro.config or in its Studio's
// sanity.config / sanity.cli rather than in a .env file. Comments and strings
// are skipped (sanitySource.ts), so a commented-out id does not count. A found
// id is only ever a suggestion matched against the person's own projects.

import fs from 'node:fs';
import path from 'node:path';
import { assert } from '../../shared/core/assert';
import { ownString, walk } from './sanitySource';

// The folders a site keeps its config in (the root, and an embedded Studio), the
// files read there, the longest file read, and the ids kept from one file.
const CONFIG_FOLDERS = ['', 'studio'] as const;
const CONFIG_FILES = [
'astro.config.mjs',
'astro.config.ts',
'astro.config.js',
'astro.config.mts',
'astro.config.cjs',
'sanity.config.ts',
'sanity.config.js',
'sanity.config.mjs',
'sanity.config.tsx',
'sanity.config.jsx',
'sanity.cli.ts',
'sanity.cli.js',
'sanity.cli.mjs',
] as const;
const CONFIG_BYTES_MAX = 256 * 1024;
const IDS_PER_FILE_MAX = 8;
// Sanity project ids are short lowercase letters and digits.
const PROJECT_ID = /^[a-z0-9]{1,32}$/;
const PROJECT_ID_KEY = /(?<![\w$])projectId\s*:/y;

/** The project ids this source text writes as `projectId: '<id>'`, at any depth, in order. */
export function configProjectIds(source: string): readonly string[] {
const ids: string[] = [];
walk(source, (index) => {
PROJECT_ID_KEY.lastIndex = index;
if (PROJECT_ID_KEY.test(source)) {
const value = ownString(source.slice(index), 'projectId');
if (value !== undefined && PROJECT_ID.test(value) && !ids.includes(value)) {
ids.push(value);
}
}
return ids.length < IDS_PER_FILE_MAX;
});
assert(ids.length <= IDS_PER_FILE_MAX, 'One file gives a bounded number of ids');
return ids;
}

/** The project ids the site's config files name, root files first; unreadable files are skipped. */
export function siteConfigProjectIds(projectRoot: string): readonly string[] {
assert(path.isAbsolute(projectRoot), 'The project root is an absolute path');
const ids: string[] = [];
for (const folder of CONFIG_FOLDERS) {
for (const name of CONFIG_FILES) {
for (const id of configProjectIds(readConfig(path.join(projectRoot, folder, name)))) {
if (!ids.includes(id)) {
ids.push(id);
}
}
}
}
assert(ids.length <= CONFIG_FOLDERS.length * CONFIG_FILES.length * IDS_PER_FILE_MAX, 'The site gives a bounded number of ids');
return ids;
}

// A config file's text, or nothing when it is missing, unreadable or too long.
function readConfig(file: string): string {
try {
if (fs.statSync(file).size > CONFIG_BYTES_MAX) {
return '';
}
return fs.readFileSync(file, 'utf8');
} catch {
return '';
}
}
1 change: 1 addition & 0 deletions shared/properties/i18n/messages/de/cmsConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const messages = {
'cmsConnections.input.secret.printable': 'Ein API-Schlüssel besteht aus druckbaren Zeichen in einer Zeile.',
'cmsConnections.kind.custom': 'Eigenes CMS',
'cmsConnections.list.noEncryption': 'Dieser Computer kann keine Schlüssel verschlüsseln, deshalb speichert Stacki keine.',
'cmsConnections.sanityDetected': 'Diese Website nutzt Sanity. Verbinde sie, um ihre Inhalte in Stacki zu bearbeiten.', // review
'cmsConnections.signIn.browser':
'Melde dich auf der Sanity-Seite in deinem Browser an und komm dann hierher zurück. Stacki erstellt einen Editor-Schlüssel für das Projekt dieser Website und behält nur diesen Schlüssel.',
'cmsConnections.signIn.cancelled': 'Anmeldung abgebrochen.',
Expand Down
1 change: 1 addition & 0 deletions shared/properties/i18n/messages/en/cmsConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const messages = {
'cmsConnections.input.secret.printable': 'An API key is printable characters on one line.',
'cmsConnections.kind.custom': 'Custom CMS',
'cmsConnections.list.noEncryption': 'This computer can’t encrypt keys, so Stacki won’t save any.',
'cmsConnections.sanityDetected': 'This site uses Sanity. Connect it to edit its content in Stacki.',
'cmsConnections.signIn.browser':
'Sign in on Sanity’s page in your browser, then come back here. Stacki creates an Editor key for this site’s project and keeps only that key.',
'cmsConnections.signIn.cancelled': 'Sign-in cancelled.',
Expand Down
1 change: 1 addition & 0 deletions shared/properties/i18n/messages/es/cmsConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const messages = {
'cmsConnections.input.secret.printable': 'Una clave de API son caracteres imprimibles en una sola línea.',
'cmsConnections.kind.custom': 'CMS personalizado',
'cmsConnections.list.noEncryption': 'Este equipo no puede cifrar claves, así que Stacki no guardará ninguna.',
'cmsConnections.sanityDetected': 'Este sitio usa Sanity. Conéctalo para editar su contenido en Stacki.', // review
'cmsConnections.signIn.browser':
'Inicia sesión en la página de Sanity en tu navegador y vuelve aquí. Stacki crea una clave de Editor para el proyecto de este sitio y guarda solo esa clave.',
'cmsConnections.signIn.cancelled': 'Inicio de sesión cancelado.',
Expand Down
1 change: 1 addition & 0 deletions shared/properties/i18n/messages/fr/cmsConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const messages = {
'cmsConnections.input.secret.printable': 'Une clé API se compose de caractères imprimables sur une seule ligne.',
'cmsConnections.kind.custom': 'CMS personnalisé',
'cmsConnections.list.noEncryption': 'Cet ordinateur ne peut pas chiffrer les clés, donc Stacki n’en enregistrera aucune.',
'cmsConnections.sanityDetected': 'Ce site utilise Sanity. Connectez-le pour modifier son contenu dans Stacki.', // review
'cmsConnections.signIn.browser':
'Connectez-vous sur la page de Sanity dans votre navigateur, puis revenez ici. Stacki crée une clé Editor pour le projet de ce site et ne conserve que cette clé.',
'cmsConnections.signIn.cancelled': 'Connexion annulée.',
Expand Down
1 change: 1 addition & 0 deletions shared/properties/i18n/messages/ptBR/cmsConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const messages = {
'cmsConnections.input.secret.printable': 'Uma chave de API são caracteres imprimíveis em uma única linha.',
'cmsConnections.kind.custom': 'CMS personalizado',
'cmsConnections.list.noEncryption': 'Este computador não consegue criptografar chaves, então o Stacki não salvará nenhuma.',
'cmsConnections.sanityDetected': 'Este site usa o Sanity. Conecte-o para editar o conteúdo dele no Stacki.', // review
'cmsConnections.signIn.browser':
'Entre na página do Sanity no seu navegador e volte aqui. O Stacki cria uma chave de Editor para o projeto deste site e guarda somente essa chave.',
'cmsConnections.signIn.cancelled': 'Login cancelado.',
Expand Down
23 changes: 23 additions & 0 deletions src/features/cmsConnections/CmsConnections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { CmsKeyForm, type CmsKeyKind } from './CmsKeyForm';
import { PayloadStatus } from './PayloadStatus';
import { EmDashButton } from './EmDashButton';
import { SkeletonRows } from '../../ui/Skeleton';
import { readText } from '../../ipc/bridge';
import { hasDependency } from '../../lib/packageManifest';

type Dialog = { readonly kind: 'sanity-login' } | { readonly kind: 'key'; readonly cms: CmsKeyKind };

Expand All @@ -23,6 +25,7 @@ export function CmsConnections({ projectPath }: { readonly projectPath: string }
const [list, setList] = useState<CmsConnectionList | undefined>(undefined);
const [error, setError] = useState<string | undefined>(undefined);
const [dialog, setDialog] = useState<Dialog | undefined>(undefined);
const sanitySite = useSanitySite(projectPath);
const refresh = useCallback(() => {
listCmsConnections(projectPath).then(setList, (reason: unknown) => setError(String(reason)));
}, [projectPath]);
Expand All @@ -39,13 +42,33 @@ export function CmsConnections({ projectPath }: { readonly projectPath: string }
{error && <ErrorToast message={error} />}
{list?.encryption === 'unavailable' && <p className="cms-connections-alert">{translate('cmsConnections.list.noEncryption')}</p>}
{list === undefined ? <SkeletonRows count={2} /> : <ConnectionRows projectPath={projectPath} connections={list.connections} onRemove={remove} />}
{list !== undefined && sanitySite && !list.connections.some((connection) => connection.kind === 'sanity') && (
<p>{translate('cmsConnections.sanityDetected')}</p>
)}
<ConnectionActions projectPath={projectPath} onOpen={setDialog} />
{dialog?.kind === 'sanity-login' && <SanitySignIn projectPath={projectPath} close={closed} />}
{dialog?.kind === 'key' && <CmsKeyForm projectPath={projectPath} cms={dialog.cms} close={closed} />}
</section>
);
}

// Whether the site's package.json lists Sanity (the Astro integration, or an embedded Studio), so the
// panel can say so while no Sanity connection exists. An unreadable package.json reads as no.
function useSanitySite(projectPath: string): boolean {
const [sanitySite, setSanitySite] = useState(false);
useEffect(() => {
let current = true;
readText(projectPath, 'package.json').then(
(text) => current && setSanitySite(hasDependency(text, '@sanity/astro') || hasDependency(text, 'sanity')),
() => current && setSanitySite(false),
);
return () => {
current = false;
};
}, [projectPath]);
return sanitySite;
}

function ConnectionRows(props: {
readonly projectPath: string;
readonly connections: readonly CmsConnection[];
Expand Down
20 changes: 1 addition & 19 deletions src/features/props/loopCatalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
// it shows there, with the same field names and choices.

import { assert } from '../../../shared/core/assert';
import { toRecord } from '../../../shared/core/record';
import { ASTRO_CONTENT_ID } from '../../../shared/properties/astroContent';
import type { RemoteSchemaField, RemoteType } from '../../../shared/properties/cmsRemoteSchema';
import { ITEM_FIELD_LIMITS, type ItemFieldDeclaration, type ItemFieldKind } from '../../editor/itemFields';
import type { LoopField, LoopFieldKind, LoopSource, LoopSourceKind } from '../../editor/loopQuery';
import { isFieldPath, ITEM_FIELD } from '../../editor/loopQuery';
import { listCmsConnections, remoteReferenceOptions } from '../../ipc/cmsConnectionsBridge';
import { readText } from '../../ipc/bridge';
import { hasDependency } from '../../lib/packageManifest';
import { remoteCollections, remoteTemplate } from '../../ipc/remoteSource';

export const LOOP_CATALOG_LIMITS = {
Expand All @@ -22,7 +22,6 @@ export const LOOP_CATALOG_LIMITS = {
projectsCachedMax: 8,
/** How deep an object's fields are listed: `location.lat`, `hero.cta.label`. */
nestingDepthMax: 4,
packageCharsMax: 1_000_000,
} as const;

export interface CatalogCollection {
Expand Down Expand Up @@ -140,23 +139,6 @@ async function sanityClientIn(projectPath: string): Promise<'available' | 'unava
return hasDependency(text, '@sanity/astro') ? 'available' : 'unavailable';
}

/** Whether a package.json's text lists `name` as a dependency of either kind. */
export function hasDependency(text: string, name: string): boolean {
if (text.length === 0 || text.length > LOOP_CATALOG_LIMITS.packageCharsMax) {
return false;
}
let manifest: unknown;
try {
manifest = JSON.parse(text);
} catch {
return false;
}
const record = toRecord(manifest);
const dependencies = toRecord(record?.['dependencies']);
const development = toRecord(record?.['devDependencies']);
return typeof dependencies?.[name] === 'string' || typeof development?.[name] === 'string';
}

/** A collection's fields, as the filter and sort menus offer them. */
export async function loadFields(projectPath: string, catalog: LoopCatalog, source: LoopSource): Promise<readonly CatalogField[] | undefined> {
const connectionId = connectionOf(catalog, source.kind);
Expand Down
25 changes: 25 additions & 0 deletions src/lib/packageManifest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// A site's package.json, read as text the renderer already has: which packages
// it depends on. Used where a feature only makes sense with a package installed
// (a Sanity loop needs @sanity/astro) or hints at one (a Sanity site, in CMS
// connections). Malformed or oversized text depends on nothing.
import { toRecord } from '../../shared/core/record';

/** The longest package.json text read. */
export const PACKAGE_MANIFEST_CHARS_MAX = 1_000_000;

/** Whether a package.json's text lists `name` as a dependency of either kind. */
export function hasDependency(text: string, name: string): boolean {
if (text.length === 0 || text.length > PACKAGE_MANIFEST_CHARS_MAX) {
return false;
}
let manifest: unknown;
try {
manifest = JSON.parse(text);
} catch {
return false;
}
const record = toRecord(manifest);
const dependencies = toRecord(record?.['dependencies']);
const development = toRecord(record?.['devDependencies']);
return typeof dependencies?.[name] === 'string' || typeof development?.[name] === 'string';
}
1 change: 1 addition & 0 deletions studio/scripts/shared-source.json
Original file line number Diff line number Diff line change
Expand Up @@ -1537,6 +1537,7 @@
"src/lib/i18n/translateRich.ts",
"src/lib/i18n/useTranslate.ts",
"src/lib/insertRank.ts",
"src/lib/packageManifest.ts",
"src/lib/pageName.ts",
"src/lib/projectPath.ts",
"src/lib/roleAccess.ts",
Expand Down
21 changes: 21 additions & 0 deletions test/electron/content/cmsConnections.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,27 @@ test('signing in saves an Editor key for the chosen project and logs the login o
}
}));

test('a site that writes its project id in a config file, not in .env, gets it suggested', () =>
withFolder(async (folder) => {
const root = path.join(folder, 'site');
fs.mkdirSync(path.join(root, 'studio'), { recursive: true });
// The shape of a site with an embedded Studio: the id in code, the dataset in .env.development.
fs.writeFileSync(path.join(root, 'astro.config.mjs'), `// projectId: 'old111'\nconst sanityProject = { projectId: "nope999" };`);
fs.writeFileSync(path.join(root, 'studio', 'sanity.cli.ts'), `export default defineCliConfig({ api: { projectId: 'abc123' } })`);
fs.writeFileSync(path.join(root, '.env.development'), 'PUBLIC_SANITY_DATASET=production\n');
const realFetch = globalThis.fetch;
const login = new SanityLogin(new CmsConnectionStore(crypt(), () => folder));
try {
globalThis.fetch = fakeSanity([]);
const id = await signIn(login, root);
const choosing = await until(login, root, id, 'choosing');
assert.deepEqual(choosing.suggestion, { projectId: 'abc123', dataset: 'production' }, 'an id outside the account is passed over');
login.request(root, { action: 'cancel', id });
} finally {
globalThis.fetch = realFetch;
}
}));

test('a role that cannot create keys says so, and nothing is saved', () =>
withFolder(async (folder) => {
const calls = [];
Expand Down
Loading
Loading