@overspace-app/client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Overspace
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @overspace-app/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Schéma de site (`defineSite`, types de champ), client de lecture typé de l'API publique Overspace v1, mode
4
+ autonome, outils sûrs (`isSafeHref`, `cssUrl`, `parseVideoUrl`) et signature des appels de revalidation
5
+ (`@overspace-app/client/revalidate`). Aucune dépendance. Licence MIT.
6
+
7
+ Pour un site Next.js, utiliser `@overspace-app/next`. Documentation : `docs/04-integration-nextjs.md` §0 (dépôt Overspace).
@@ -0,0 +1,110 @@
1
+ import { type CompiledSchema, type PageContent, type PageKey, type SectionContent, type SectionKey, type SiteDefinition } from '../schema/index.js';
2
+ /**
3
+ * Client de lecture typé de l'API publique Overspace v1 (ADR 0007) — sans dépendance, utilisable partout
4
+ * (Node, edge, autre framework). `@overspace-app/next` l'enveloppe pour le cache et l'ISR de Next.js.
5
+ *
6
+ * Typage : passer `config` (le `overspace.config.ts` du site) donne des retours typés et envoie l'empreinte du
7
+ * schéma (`Overspace-Schema-Hash`). Sans réseau (mode autonome, D27) : `bundle` = export du site.
8
+ * La clé API ne doit être utilisée que côté serveur.
9
+ */
10
+ export type ResourceKind = 'site' | 'section' | 'page' | 'articles' | 'article';
11
+ export type ClientOptions<D extends SiteDefinition> = {
12
+ /** Origine d'Overspace, ex. https://admin.overspace.app (https obligatoire, http seulement vers localhost). */
13
+ url?: string;
14
+ /** Slug du site. */
15
+ site?: string;
16
+ /** Clé API du site (portée `content:read`). Jamais côté navigateur. */
17
+ apiKey?: string;
18
+ /** Schéma du site (`overspace.config.ts`) : typage, valeurs par défaut, empreinte envoyée. */
19
+ config?: D;
20
+ /** Mode autonome : lecture depuis un export local, sans appel réseau. */
21
+ bundle?: ExportBundle;
22
+ fetch?: typeof fetch;
23
+ /** Délai maximal d'un appel (défaut 5 s). */
24
+ timeoutMs?: number;
25
+ /** Options de requête par ressource (utilisé par @overspace-app/next pour le cache). */
26
+ requestInit?: (kind: ResourceKind, key?: string) => RequestInit & Record<string, unknown>;
27
+ };
28
+ export type ArticleSummary = {
29
+ id: string;
30
+ title: string;
31
+ slug: string;
32
+ excerpt: string | null;
33
+ cover_url: string | null;
34
+ category: string | null;
35
+ locale: string | null;
36
+ published_at: string | null;
37
+ views?: number;
38
+ };
39
+ export type Article = ArticleSummary & {
40
+ content: unknown;
41
+ meta_title: string | null;
42
+ meta_description: string | null;
43
+ updated_at: string;
44
+ };
45
+ export type ArticleList = {
46
+ total: number;
47
+ limit: number;
48
+ offset: number;
49
+ articles: ArticleSummary[];
50
+ };
51
+ export type SiteInfo = {
52
+ site: {
53
+ name: string;
54
+ slug: string;
55
+ domain: string | null;
56
+ };
57
+ schema: {
58
+ hash: string;
59
+ version: number;
60
+ locales: CompiledSchema['locales'];
61
+ pages: CompiledSchema['pages'];
62
+ } | null;
63
+ };
64
+ /**
65
+ * Export d'un site (mode autonome) : même contenu que l'API, figé dans le dépôt du site.
66
+ * Produit par `overspace detach` (étape 2.7) ; médias déjà réécrits en chemins locaux.
67
+ */
68
+ export type ExportBundle = {
69
+ formatVersion: 1;
70
+ site: SiteInfo['site'];
71
+ schema: CompiledSchema;
72
+ sections: Record<string, {
73
+ content: unknown;
74
+ translations?: unknown;
75
+ }>;
76
+ articles: Article[];
77
+ };
78
+ export declare class OverspaceError extends Error {
79
+ readonly status: number;
80
+ readonly code: string;
81
+ /** Panne passagère (réseau, délai, 5xx, 429) : le site doit garder son dernier rendu plutôt que d'afficher des défauts (R-39). */
82
+ readonly retryable: boolean;
83
+ constructor(message: string, status: number, code: string,
84
+ /** Panne passagère (réseau, délai, 5xx, 429) : le site doit garder son dernier rendu plutôt que d'afficher des défauts (R-39). */
85
+ retryable: boolean);
86
+ }
87
+ type Locale = {
88
+ locale?: string;
89
+ };
90
+ export declare function createOverspaceClient<D extends SiteDefinition = SiteDefinition>(options: ClientOptions<D>): {
91
+ /** Mode de lecture : `api` (réseau) ou `standalone` (export local). */
92
+ mode: "standalone" | "api";
93
+ /** Schéma compilé du site (si `config` ou `bundle` est fourni). */
94
+ schema: CompiledSchema | null;
95
+ site(): Promise<SiteInfo>;
96
+ section<K extends SectionKey<D>>(key: K, opts?: Locale): Promise<SectionContent<D, K>>;
97
+ page<P extends PageKey<D>>(page: P, opts?: Locale): Promise<PageContent<D, P>>;
98
+ articles(opts?: {
99
+ limit?: number;
100
+ offset?: number;
101
+ category?: string;
102
+ locale?: string;
103
+ }): Promise<ArticleList>;
104
+ /** Un article publié, ou `null` s'il n'existe pas (ou n'est pas publié). */
105
+ article(slug: string): Promise<Article | null>;
106
+ /** Valeurs par défaut d'une section, sans réseau (premier rendu sans cache, développement). */
107
+ defaults<K extends SectionKey<D>>(key: K): SectionContent<D, K>;
108
+ };
109
+ export type OverspaceClient<D extends SiteDefinition = SiteDefinition> = ReturnType<typeof createOverspaceClient<D>>;
110
+ export {};
@@ -0,0 +1,168 @@
1
+ import { applyReferences, referenceIds, compileSite, normalizeSection, pickLocale, resolveSection, schemaHash, } from '../schema/index.js';
2
+ export class OverspaceError extends Error {
3
+ status;
4
+ code;
5
+ retryable;
6
+ constructor(message, status, code, retryable) {
7
+ super(message);
8
+ this.status = status;
9
+ this.code = code;
10
+ this.retryable = retryable;
11
+ this.name = 'OverspaceError';
12
+ }
13
+ }
14
+ export function createOverspaceClient(options) {
15
+ const compiled = options.config ? compileSite(options.config) : null;
16
+ const hashPromise = compiled ? schemaHash(compiled) : Promise.resolve(null);
17
+ const doFetch = options.fetch ?? globalThis.fetch;
18
+ const timeoutMs = options.timeoutMs ?? 5_000;
19
+ if (!options.bundle) {
20
+ if (!options.url || !options.site || !options.apiKey) {
21
+ throw new OverspaceError('Overspace : url, site et apiKey sont requis (ou un export pour le mode autonome).', 0, 'CONFIG', false);
22
+ }
23
+ assertSafeOrigin(options.url);
24
+ if (!/^[a-z0-9-]{1,63}$/.test(options.site))
25
+ throw new OverspaceError('Overspace : slug de site invalide.', 0, 'CONFIG', false);
26
+ }
27
+ async function get(kind, path, key) {
28
+ const base = options.url.replace(/\/+$/, '');
29
+ const headers = { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json' };
30
+ const h = await hashPromise;
31
+ if (h)
32
+ headers['Overspace-Schema-Hash'] = h;
33
+ const extra = options.requestInit?.(kind, key) ?? {};
34
+ let res;
35
+ try {
36
+ res = await doFetch(`${base}/api/v1/${options.site}${path}`, {
37
+ ...extra,
38
+ method: 'GET',
39
+ headers: { ...headers, ...(extra.headers ?? {}) },
40
+ redirect: 'error',
41
+ signal: AbortSignal.timeout(timeoutMs),
42
+ });
43
+ }
44
+ catch (e) {
45
+ throw new OverspaceError(`Overspace injoignable (${e.name})`, 0, 'NETWORK', true);
46
+ }
47
+ const body = (await res.json().catch(() => null));
48
+ if (!res.ok || !body?.ok) {
49
+ const retryable = res.status === 429 || res.status >= 500;
50
+ throw new OverspaceError(body?.message ?? `Erreur Overspace (${res.status})`, res.status, body?.error ?? 'HTTP_' + res.status, retryable);
51
+ }
52
+ return body;
53
+ }
54
+ function requireSection(key) {
55
+ if (compiled && !resolveSection(compiled, key)) {
56
+ throw new OverspaceError(`Section « ${key} » absente du schéma du site (overspace.config.ts).`, 0, 'UNKNOWN_SECTION', false);
57
+ }
58
+ }
59
+ const bundle = options.bundle;
60
+ let summaries = null;
61
+ function articleSummaries() {
62
+ summaries ??= new Map(bundle.articles.map((a) => [
63
+ a.id,
64
+ { id: a.id, title: a.title, slug: a.slug, excerpt: a.excerpt, cover_url: a.cover_url, category: a.category, locale: a.locale, published_at: a.published_at },
65
+ ]));
66
+ return summaries;
67
+ }
68
+ function fromBundle(sectionKeys, requestedLocale) {
69
+ const schema = bundle.schema;
70
+ const locale = pickLocale(schema, requestedLocale ?? null);
71
+ const out = {};
72
+ for (const key of sectionKeys) {
73
+ const section = resolveSection(schema, key);
74
+ if (!section)
75
+ continue;
76
+ const row = bundle.sections[section.key];
77
+ const values = normalizeSection(section, row?.content, row?.translations, locale, schema.locales.default);
78
+ out[section.key] = referenceIds(section, values).length ? applyReferences(section, values, articleSummaries()) : values;
79
+ }
80
+ return { locale, sections: out };
81
+ }
82
+ return {
83
+ mode: bundle ? 'standalone' : 'api',
84
+ schema: (compiled ?? bundle?.schema ?? null),
85
+ async site() {
86
+ if (bundle)
87
+ return { site: bundle.site, schema: { hash: (await schemaHash(bundle.schema)), version: 0, locales: bundle.schema.locales, pages: bundle.schema.pages } };
88
+ const r = await get('site', '/site');
89
+ return { site: r.site, schema: r.schema };
90
+ },
91
+ async section(key, opts = {}) {
92
+ if (bundle)
93
+ return fromBundle([key], opts.locale).sections[key];
94
+ requireSection(key);
95
+ const q = opts.locale ? `?locale=${encodeURIComponent(opts.locale)}` : '';
96
+ const r = await get('section', `/content/${encodeURIComponent(key)}${q}`, key);
97
+ return r.content;
98
+ },
99
+ async page(page, opts = {}) {
100
+ if (bundle) {
101
+ const keys = bundle.schema.sections.filter((s) => s.page === page).map((s) => s.key);
102
+ return fromBundle(keys, opts.locale).sections;
103
+ }
104
+ if (compiled && !compiled.pages.some((p) => p.key === page)) {
105
+ throw new OverspaceError(`Page « ${page} » absente du schéma du site.`, 0, 'UNKNOWN_PAGE', false);
106
+ }
107
+ const q = opts.locale ? `?locale=${encodeURIComponent(opts.locale)}` : '';
108
+ const r = await get('page', `/pages/${encodeURIComponent(page)}${q}`, page);
109
+ return r.sections;
110
+ },
111
+ async articles(opts = {}) {
112
+ if (bundle) {
113
+ let list = [...bundle.articles];
114
+ if (opts.category)
115
+ list = list.filter((a) => a.category === opts.category);
116
+ if (opts.locale)
117
+ list = list.filter((a) => (a.locale ?? bundle.schema.locales.default) === opts.locale);
118
+ const offset = opts.offset ?? 0;
119
+ const limit = opts.limit ?? 10;
120
+ return { total: list.length, limit, offset, articles: list.slice(offset, offset + limit) };
121
+ }
122
+ const q = new URLSearchParams();
123
+ for (const [k, v] of Object.entries(opts))
124
+ if (v !== undefined && v !== '')
125
+ q.set(k, String(v));
126
+ const s = q.toString();
127
+ const r = await get('articles', `/articles${s ? `?${s}` : ''}`);
128
+ return { total: r.total, limit: r.limit, offset: r.offset, articles: r.articles };
129
+ },
130
+ async article(slug) {
131
+ if (!/^[a-z0-9-]{1,100}$/.test(slug))
132
+ return null;
133
+ if (bundle)
134
+ return bundle.articles.find((a) => a.slug === slug) ?? null;
135
+ try {
136
+ const r = await get('article', `/articles/${slug}`, slug);
137
+ return r.article;
138
+ }
139
+ catch (e) {
140
+ if (e instanceof OverspaceError && e.status === 404)
141
+ return null;
142
+ throw e;
143
+ }
144
+ },
145
+ defaults(key) {
146
+ const schema = compiled ?? bundle?.schema;
147
+ const section = schema ? resolveSection(schema, key) : null;
148
+ if (!schema || !section)
149
+ throw new OverspaceError(`Section « ${key} » inconnue.`, 0, 'UNKNOWN_SECTION', false);
150
+ return normalizeSection(section, {}, {}, schema.locales.default, schema.locales.default);
151
+ },
152
+ };
153
+ }
154
+ function assertSafeOrigin(url) {
155
+ let u;
156
+ try {
157
+ u = new URL(url);
158
+ }
159
+ catch {
160
+ throw new OverspaceError('Overspace : URL invalide.', 0, 'CONFIG', false);
161
+ }
162
+ const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
163
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {
164
+ throw new OverspaceError('Overspace : https obligatoire (http seulement vers localhost).', 0, 'CONFIG', false);
165
+ }
166
+ if (u.username || u.password)
167
+ throw new OverspaceError('Overspace : identifiants interdits dans l’URL.', 0, 'CONFIG', false);
168
+ }
package/dist/css.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Insertion sûre d'une image de contenu dans du CSS (revue Fable R-32).
3
+ *
4
+ * Les sources d'image acceptées par Overspace peuvent contenir une apostrophe ou des parenthèses (noms de
5
+ * fichiers d'origine). Sûr dans un attribut, ou dans `url("…")` — pas dans `url('…')` ni `url(…)`.
6
+ * Toujours écrire : `style={{ backgroundImage: cssUrl(src) }}`, jamais une concaténation.
7
+ */
8
+ export declare function cssUrl(src: string | null | undefined): string;
package/dist/css.js ADDED
@@ -0,0 +1,6 @@
1
+ export function cssUrl(src) {
2
+ if (!src)
3
+ return 'none';
4
+ const escaped = src.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\n\r\f]/g, '');
5
+ return `url("${escaped}")`;
6
+ }
@@ -0,0 +1,6 @@
1
+ export * from './client/index.js';
2
+ export * from './css.js';
3
+ export { defineSite, field } from './schema/index.js';
4
+ export type { SiteDefinition, SectionContent, PageContent, SectionKey, PageKey, ImageValue, LinkValue, RichTextDoc } from './schema/index.js';
5
+ export { parseVideoUrl, canonicalVideoUrl, isValidVideo } from './video.js';
6
+ export { isSafeHref } from './schema/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './client/index.js';
2
+ export * from './css.js';
3
+ export { defineSite, field } from './schema/index.js';
4
+ export { parseVideoUrl, canonicalVideoUrl, isValidVideo } from './video.js';
5
+ export { isSafeHref } from './schema/index.js';
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Protocole d'APERÇU v1 entre le dashboard Overspace (fenêtre parente) et la page d'aperçu du site (iframe)
3
+ * — design §5.3 et §7, revue Fable R-18. Messages `postMessage`, toujours avec `v: 1` :
4
+ *
5
+ * site → dashboard { type: 'overspace:ready', v: 1 } la page d'aperçu écoute
6
+ * dashboard → site { type: 'overspace:preview', v: 1, page, sections } brouillon de la page affichée
7
+ * dashboard → site { type: 'overspace:scroll', v: 1, section } aller à une section
8
+ *
9
+ * `sections` : `{ [clé de section]: contenu brouillon }`, médias déjà résolus en URL, articles liés non résolus
10
+ * (`null` dans l'aperçu). Contrôles des deux côtés : origine exacte attendue ET fenêtre émettrice (`source`) ;
11
+ * le site revalide le brouillon avec son propre schéma avant de l'afficher.
12
+ * Le chemin de la page d'aperçu sur le site : `/overspace-preview` + chemin de la page (`/`, `/offre`…).
13
+ */
14
+ import { type CompiledSchema } from './schema/index.js';
15
+ export declare const PREVIEW_PROTOCOL_VERSION = 1;
16
+ export declare const PREVIEW_PATH = "/overspace-preview";
17
+ export declare const PREVIEW_V1: {
18
+ readonly ready: "overspace:ready";
19
+ readonly preview: "overspace:preview";
20
+ readonly scroll: "overspace:scroll";
21
+ };
22
+ /** Taille maximale acceptée d'un brouillon reçu (octets JSON) : au-delà, ignoré. */
23
+ export declare const PREVIEW_MAX_BYTES = 2000000;
24
+ /** URL de la page d'aperçu d'une page du site. */
25
+ export declare function previewUrl(siteBase: string, pagePath: string): string;
26
+ export type PreviewMessage = {
27
+ type: typeof PREVIEW_V1.ready;
28
+ v: 1;
29
+ } | {
30
+ type: typeof PREVIEW_V1.preview;
31
+ v: 1;
32
+ page: string;
33
+ sections: Record<string, unknown>;
34
+ } | {
35
+ type: typeof PREVIEW_V1.scroll;
36
+ v: 1;
37
+ section: string;
38
+ };
39
+ /** Lecture défensive d'un message reçu (forme seulement — la confiance vient de l'origine et de la source). */
40
+ export declare function readPreviewMessage(data: unknown): PreviewMessage | null;
41
+ /**
42
+ * Brouillon reçu → sections de la page, revalidées par le schéma du SITE (R-18) : sections d'autres pages,
43
+ * champs inconnus et valeurs de mauvais type écartés ; brouillon trop gros ou page inconnue → null.
44
+ */
45
+ export declare function normalizeDraft(schema: CompiledSchema, page: string, sections: Record<string, unknown>): Record<string, Record<string, unknown>> | null;
@@ -0,0 +1,51 @@
1
+ import { normalizeSection } from './schema/index.js';
2
+ export const PREVIEW_PROTOCOL_VERSION = 1;
3
+ export const PREVIEW_PATH = '/overspace-preview';
4
+ export const PREVIEW_V1 = {
5
+ ready: 'overspace:ready',
6
+ preview: 'overspace:preview',
7
+ scroll: 'overspace:scroll',
8
+ };
9
+ export const PREVIEW_MAX_BYTES = 2_000_000;
10
+ export function previewUrl(siteBase, pagePath) {
11
+ const base = siteBase.replace(/\/+$/, '');
12
+ const path = pagePath.startsWith('/') ? pagePath : '/' + pagePath;
13
+ return base + PREVIEW_PATH + (path === '/' ? '/' : path);
14
+ }
15
+ export function readPreviewMessage(data) {
16
+ if (!data || typeof data !== 'object')
17
+ return null;
18
+ const d = data;
19
+ if (d.v !== PREVIEW_PROTOCOL_VERSION || typeof d.type !== 'string')
20
+ return null;
21
+ if (d.type === PREVIEW_V1.ready)
22
+ return { type: PREVIEW_V1.ready, v: 1 };
23
+ if (d.type === PREVIEW_V1.scroll && typeof d.section === 'string' && /^[a-z][a-z0-9-]{0,49}$/.test(d.section)) {
24
+ return { type: PREVIEW_V1.scroll, v: 1, section: d.section };
25
+ }
26
+ if (d.type === PREVIEW_V1.preview && typeof d.page === 'string' && /^[a-z][a-z0-9-]{0,49}$/.test(d.page) && d.sections && typeof d.sections === 'object' && !Array.isArray(d.sections)) {
27
+ return { type: PREVIEW_V1.preview, v: 1, page: d.page, sections: d.sections };
28
+ }
29
+ return null;
30
+ }
31
+ export function normalizeDraft(schema, page, sections) {
32
+ if (!schema.pages.some((p) => p.key === page))
33
+ return null;
34
+ let size = 0;
35
+ try {
36
+ size = JSON.stringify(sections).length;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ if (size > PREVIEW_MAX_BYTES)
42
+ return null;
43
+ const out = {};
44
+ for (const s of schema.sections) {
45
+ if (s.page !== page)
46
+ continue;
47
+ const normalized = normalizeSection(s, sections[s.key], undefined, schema.locales.default, schema.locales.default);
48
+ out[s.key] = Object.fromEntries(s.fields.map((f) => [f.key, normalized[f.key]]));
49
+ }
50
+ return out;
51
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Signature des appels de revalidation Overspace → site (ADR 0007 §4, revue Fable R-12 / R-13).
3
+ *
4
+ * En-tête : `x-overspace-signature: t=<secondes UNIX>,v1=<hex>` où
5
+ * v1 = HMAC-SHA256(secret, `${t}.${corps brut}`).
6
+ * Le site recalcule la signature sur le corps BRUT reçu (avant tout décodage JSON), vérifie l'horodatage
7
+ * (fenêtre de 5 minutes, contre le rejeu) et compare à temps constant.
8
+ * Web Crypto : Node ≥ 20, edge, navigateurs. Aucune dépendance.
9
+ */
10
+ export declare const SIGNATURE_HEADER = "x-overspace-signature";
11
+ export declare const DEFAULT_TOLERANCE_SECONDS = 300;
12
+ /** Valeur de l'en-tête à envoyer pour un corps donné. */
13
+ export declare function signRevalidation(secret: string, rawBody: string, nowSeconds?: number): Promise<string>;
14
+ export type VerifyResult = {
15
+ ok: true;
16
+ } | {
17
+ ok: false;
18
+ reason: 'MISSING' | 'MALFORMED' | 'EXPIRED' | 'BAD_SIGNATURE' | 'NO_SECRET';
19
+ };
20
+ /**
21
+ * Vérifie un appel reçu. `secrets` : le secret courant, et l'ancien pendant une rotation (24 h, R-13).
22
+ * Le corps doit être le texte BRUT de la requête.
23
+ */
24
+ export declare function verifyRevalidation(secrets: string | readonly string[], header: string | null | undefined, rawBody: string, nowSeconds?: number, toleranceSeconds?: number): Promise<VerifyResult>;
@@ -0,0 +1,39 @@
1
+ export const SIGNATURE_HEADER = 'x-overspace-signature';
2
+ export const DEFAULT_TOLERANCE_SECONDS = 300;
3
+ const enc = new TextEncoder();
4
+ async function hmacHex(secret, message) {
5
+ const key = await globalThis.crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
6
+ const sig = await globalThis.crypto.subtle.sign('HMAC', key, enc.encode(message));
7
+ return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, '0')).join('');
8
+ }
9
+ export async function signRevalidation(secret, rawBody, nowSeconds = Math.floor(Date.now() / 1000)) {
10
+ if (!secret)
11
+ throw new Error('signRevalidation : secret vide');
12
+ return `t=${nowSeconds},v1=${await hmacHex(secret, `${nowSeconds}.${rawBody}`)}`;
13
+ }
14
+ function timingSafeEqualHex(a, b) {
15
+ if (a.length !== b.length)
16
+ return false;
17
+ let diff = 0;
18
+ for (let i = 0; i < a.length; i++)
19
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
20
+ return diff === 0;
21
+ }
22
+ export async function verifyRevalidation(secrets, header, rawBody, nowSeconds = Math.floor(Date.now() / 1000), toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
23
+ const list = (Array.isArray(secrets) ? secrets : [secrets]).filter((s) => typeof s === 'string' && s !== '');
24
+ if (list.length === 0)
25
+ return { ok: false, reason: 'NO_SECRET' };
26
+ if (!header)
27
+ return { ok: false, reason: 'MISSING' };
28
+ const m = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/.exec(header.trim());
29
+ if (!m)
30
+ return { ok: false, reason: 'MALFORMED' };
31
+ const t = Number(m[1]);
32
+ if (Math.abs(nowSeconds - t) > toleranceSeconds)
33
+ return { ok: false, reason: 'EXPIRED' };
34
+ for (const secret of list) {
35
+ if (timingSafeEqualHex(await hmacHex(secret, `${t}.${rawBody}`), m[2]))
36
+ return { ok: true };
37
+ }
38
+ return { ok: false, reason: 'BAD_SIGNATURE' };
39
+ }
@@ -0,0 +1,88 @@
1
+ import { type AnyField, type ScalarField } from './fields.js';
2
+ import type { SiteDefinition } from './site.js';
3
+ /**
4
+ * Schéma compilé (format 1) : la forme JSON envoyée à Overspace par `overspace schema push` et
5
+ * stockée dans `site_schemas.schema`. Tableaux plutôt qu'objets : l'ordre d'affichage doit
6
+ * survivre au stockage (Postgres `jsonb` ne conserve pas l'ordre des clés d'un objet).
7
+ *
8
+ * Les règles de cohérence (`checkCompiledSchema`) sont écrites UNE seule fois, ici : la CLI les
9
+ * applique avant d'envoyer, le serveur les ré-applique sur ce qu'il reçoit (entrée non fiable),
10
+ * après avoir vérifié la forme avec Zod.
11
+ */
12
+ export declare const SCHEMA_FORMAT_VERSION = 1;
13
+ export type CompiledScalarField = {
14
+ key: string;
15
+ } & ScalarField;
16
+ export type CompiledListField = Omit<Extract<AnyField, {
17
+ type: 'list';
18
+ }>, 'item' | 'default'> & {
19
+ key: string;
20
+ item: CompiledScalarField[];
21
+ default?: Array<Record<string, unknown>>;
22
+ };
23
+ export type CompiledField = CompiledScalarField | CompiledListField;
24
+ export type CompiledSection = {
25
+ key: string;
26
+ label: string;
27
+ page: string;
28
+ renamedFrom?: string;
29
+ fields: CompiledField[];
30
+ };
31
+ export type CompiledPage = {
32
+ key: string;
33
+ label: string;
34
+ path: string;
35
+ };
36
+ export type CompiledSchema = {
37
+ formatVersion: typeof SCHEMA_FORMAT_VERSION;
38
+ locales: {
39
+ default: string;
40
+ others: string[];
41
+ };
42
+ pages: CompiledPage[];
43
+ sections: CompiledSection[];
44
+ articles: {
45
+ enabled: boolean;
46
+ categories: string[];
47
+ };
48
+ };
49
+ export declare const LIMITS: {
50
+ readonly pages: 100;
51
+ readonly sections: 200;
52
+ readonly fieldsPerSection: 100;
53
+ readonly fieldsPerListItem: 30;
54
+ readonly listItems: 100;
55
+ readonly galleryImages: 100;
56
+ readonly selectOptions: 200;
57
+ readonly categories: 50;
58
+ readonly locales: 10;
59
+ readonly label: 120;
60
+ readonly hint: 500;
61
+ readonly path: 200;
62
+ readonly key: 50;
63
+ readonly textMaxLength: 100000;
64
+ };
65
+ /**
66
+ * Section et page : kebab-case, commence par une lettre (une clé entièrement numérique, `404`, serait classée
67
+ * en tête par `Object.entries` et casserait l'ordre du fichier — revue Fable R-33.2).
68
+ */
69
+ export declare const SECTION_KEY_RE: RegExp;
70
+ /** Champ : camelCase / snake_case, commence par une lettre. */
71
+ export declare const FIELD_KEY_RE: RegExp;
72
+ /** Langue : `fr`, `en`, `pt-BR`. */
73
+ export declare const LOCALE_RE: RegExp;
74
+ /** Chemin de page : absolu, sans `..`, `//`, espace ni caractère de contrôle. */
75
+ export declare const PAGE_PATH_RE: RegExp;
76
+ /** Nombre maximal de problèmes renvoyés (la CLI les affiche dans un terminal). */
77
+ export declare const MAX_PROBLEMS = 50;
78
+ export declare class SchemaError extends Error {
79
+ readonly problems: string[];
80
+ constructor(problems: string[]);
81
+ }
82
+ /** Convertit `overspace.config.ts` en schéma compilé, ou lève `SchemaError` avec TOUS les problèmes trouvés. */
83
+ export declare function compileSite(def: SiteDefinition): CompiledSchema;
84
+ /**
85
+ * Règles de cohérence d'un schéma compilé. Renvoie la liste des problèmes (vide = valide).
86
+ * Suppose une forme déjà correcte (types de base vérifiés par Zod côté serveur, par TypeScript côté CLI).
87
+ */
88
+ export declare function checkCompiledSchema(s: CompiledSchema): string[];