@obelism/content 0.28.3 → 0.29.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/dist/bridge.d.mts +1 -1
- package/dist/bridge.d.mts.map +1 -1
- package/dist/bridge.d.ts +1 -1
- package/dist/bridge.d.ts.map +1 -1
- package/dist/bridge.global.js +4 -4
- package/dist/bridge.js +423 -374
- package/dist/bridge.mjs +424 -375
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +44 -4
- package/dist/index.mjs +45 -5
- package/dist/{preview-el7sfk3h.mjs → preview-9qff497d.mjs} +1 -1
- package/dist/site-j5kqgtj3.js +368 -0
- package/dist/site-m85jdjid.mjs +360 -0
- package/dist/site.js +10 -340
- package/dist/site.mjs +2 -336
- package/dist/{types-b6jbj3g6.d.ts → types-mqo1osjh.d.ts} +2 -1
- package/dist/{types-b6jbj3g6.d.ts.map → types-mqo1osjh.d.ts.map} +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { n as normalizeUrl, a as DEFAULT_TIMEOUT, D as DEFAULT_URL } from './config-c6qktlz6.mjs';
|
|
2
|
+
|
|
3
|
+
// The cookies in a `Cookie` header or `document.cookie`, by name: the first
|
|
4
|
+
// of each name, percent-decoded when it decodes.
|
|
5
|
+
const parseCookies = (header)=>{
|
|
6
|
+
const cookies = new Map();
|
|
7
|
+
for (const part of header.split(';')){
|
|
8
|
+
const index = part.indexOf('=');
|
|
9
|
+
if (index < 0) continue;
|
|
10
|
+
const name = part.slice(0, index).trim();
|
|
11
|
+
if (!name || cookies.has(name)) continue;
|
|
12
|
+
try {
|
|
13
|
+
cookies.set(name, decodeURIComponent(part.slice(index + 1).trim()));
|
|
14
|
+
} catch {
|
|
15
|
+
cookies.set(name, part.slice(index + 1).trim());
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return cookies;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// What a site's shop pages come in: the bridge's SHOP table is keyed by the
|
|
22
|
+
// type, and the site's API routes are built from the list.
|
|
23
|
+
const SHOP_KINDS = [
|
|
24
|
+
'product',
|
|
25
|
+
'collection'
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
// Every call the bridge makes through the site's `/cms/api/…`, and what the
|
|
29
|
+
// site's handler (`createSiteEditing`, ./site) lets through: one list, so a
|
|
30
|
+
// call the bridge makes can't be one the proxy refuses.
|
|
31
|
+
//
|
|
32
|
+
// The bridge goes through the site because the CMS token stays in an httpOnly
|
|
33
|
+
// cookie on it (the CMS's docs/adr/0010).
|
|
34
|
+
const entryPath = (entryId, suffix = '')=>`entries/${encodeURIComponent(entryId)}${suffix}`;
|
|
35
|
+
const siteApi = {
|
|
36
|
+
session: ()=>'session',
|
|
37
|
+
pages: ()=>'pages',
|
|
38
|
+
stats: ()=>'stats',
|
|
39
|
+
form: ()=>'form',
|
|
40
|
+
createEntry: ()=>'entries',
|
|
41
|
+
shopPages: (kind)=>`${kind}-pages`,
|
|
42
|
+
entry: (entryId)=>entryPath(entryId),
|
|
43
|
+
preview: (entryId)=>entryPath(entryId, '/preview'),
|
|
44
|
+
prompt: (entryId)=>entryPath(entryId, '/prompt'),
|
|
45
|
+
view: (entryId)=>entryPath(entryId, '/view'),
|
|
46
|
+
apply: (entryId)=>entryPath(entryId, '/apply'),
|
|
47
|
+
save: (entryId)=>entryPath(entryId, '/save'),
|
|
48
|
+
publish: (entryId)=>entryPath(entryId, '/publish')
|
|
49
|
+
};
|
|
50
|
+
// Each call's route on the CMS's site API, as the site's proxy matches it: an
|
|
51
|
+
// entry id is one path segment of word characters or dashes.
|
|
52
|
+
const ROUTE = {
|
|
53
|
+
session: 'session',
|
|
54
|
+
pages: 'pages',
|
|
55
|
+
stats: 'stats',
|
|
56
|
+
form: 'form',
|
|
57
|
+
createEntry: 'entries',
|
|
58
|
+
shopPages: `(?:${SHOP_KINDS.join('|')})-pages`,
|
|
59
|
+
entry: 'entries/[\\w-]+',
|
|
60
|
+
preview: 'entries/[\\w-]+/preview',
|
|
61
|
+
prompt: 'entries/[\\w-]+/prompt',
|
|
62
|
+
view: 'entries/[\\w-]+/view',
|
|
63
|
+
apply: 'entries/[\\w-]+/apply',
|
|
64
|
+
save: 'entries/[\\w-]+/save',
|
|
65
|
+
publish: 'entries/[\\w-]+/publish'
|
|
66
|
+
};
|
|
67
|
+
// The method each call is made with. The proxy lets only that one through.
|
|
68
|
+
const SITE_METHOD = {
|
|
69
|
+
session: 'GET',
|
|
70
|
+
pages: 'GET',
|
|
71
|
+
stats: 'POST',
|
|
72
|
+
form: 'POST',
|
|
73
|
+
createEntry: 'POST',
|
|
74
|
+
shopPages: 'POST',
|
|
75
|
+
entry: 'GET',
|
|
76
|
+
preview: 'POST',
|
|
77
|
+
prompt: 'POST',
|
|
78
|
+
view: 'POST',
|
|
79
|
+
apply: 'POST',
|
|
80
|
+
save: 'POST',
|
|
81
|
+
publish: 'POST'
|
|
82
|
+
};
|
|
83
|
+
// Whether the site's proxy lets this method and route through.
|
|
84
|
+
const siteApiAllows = (method, route)=>Object.keys(siteApi).some((name)=>SITE_METHOD[name] === method && new RegExp(`^${ROUTE[name]}$`).test(route));
|
|
85
|
+
|
|
86
|
+
// Editing on your own site, outside the visual editor
|
|
87
|
+
// (https://content.obelism.studio/docs/guides/site-editing). One handler
|
|
88
|
+
// serves everything under `/cms` (the `basePath`) on your site:
|
|
89
|
+
//
|
|
90
|
+
// - `/cms/login?return_to=/pricing` — sends the browser to Obelism Content
|
|
91
|
+
// to sign in, with a PKCE challenge, and…
|
|
92
|
+
// - `/cms/callback` — …takes it back: trades the one-time code for a site
|
|
93
|
+
// token, keeps it in an httpOnly cookie, calls `onSignIn` (turn on your
|
|
94
|
+
// framework's draft mode there) and returns to `return_to`.
|
|
95
|
+
// - `/cms/logout` — ends the session in the CMS, clears the cookies, calls
|
|
96
|
+
// `onSignOut`.
|
|
97
|
+
// - `/cms/api/…` — what the bridge's prompt bar calls in the browser,
|
|
98
|
+
// forwarded to the CMS with the token. The token never reaches page
|
|
99
|
+
// scripts.
|
|
100
|
+
//
|
|
101
|
+
// While signed in, render drafts by reading the delivery API with the token
|
|
102
|
+
// (`readSiteToken`), and the bridge shows the prompt bar with Save and
|
|
103
|
+
// Publish.
|
|
104
|
+
const SITE_TOKEN_COOKIE = 'obelism_content_token';
|
|
105
|
+
// Readable by the page: tells the bridge the site is being edited, and where
|
|
106
|
+
// this handler lives. Holds no secret.
|
|
107
|
+
const SITE_EDITING_COOKIE = 'obelism_content_editing';
|
|
108
|
+
const FLOW_COOKIE = 'obelism_content_flow';
|
|
109
|
+
// The bridge sends it with every write, which a cross-site form can't.
|
|
110
|
+
const SITE_REQUEST_HEADER = 'x-obelism-content';
|
|
111
|
+
const SITE_PATH = '/api/site/v1';
|
|
112
|
+
const FLOW_MAX_AGE = 10 * 60;
|
|
113
|
+
// The site token from a Cookie header (or a framework's cookie store), or
|
|
114
|
+
// null when not signed in to edit:
|
|
115
|
+
//
|
|
116
|
+
// const token = readSiteToken(request.headers.get('cookie'))
|
|
117
|
+
// const content = token ? new ContentClient({ token, init: { cache: 'no-store' } }) : delivery
|
|
118
|
+
const readSiteToken = (cookies)=>{
|
|
119
|
+
if (!cookies) return null;
|
|
120
|
+
if (typeof cookies !== 'string') return cookies.get(SITE_TOKEN_COOKIE)?.value || null;
|
|
121
|
+
return parseCookies(cookies).get(SITE_TOKEN_COOKIE) || null;
|
|
122
|
+
};
|
|
123
|
+
const serializeCookie = (name, value, { maxAge, path, httpOnly, secure })=>[
|
|
124
|
+
`${name}=${encodeURIComponent(value)}`,
|
|
125
|
+
`Path=${path}`,
|
|
126
|
+
`Max-Age=${Math.max(0, Math.floor(maxAge))}`,
|
|
127
|
+
// Also Expires: Next.js re-serializes response cookies when draft mode
|
|
128
|
+
// changes, and drops a Max-Age of 0.
|
|
129
|
+
`Expires=${new Date(maxAge > 0 ? Date.now() + maxAge * 1000 : 0).toUTCString()}`,
|
|
130
|
+
'SameSite=Lax',
|
|
131
|
+
httpOnly && 'HttpOnly',
|
|
132
|
+
secure && 'Secure'
|
|
133
|
+
].filter(Boolean).join('; ');
|
|
134
|
+
const base64Url = (bytes)=>{
|
|
135
|
+
let binary = '';
|
|
136
|
+
for (const byte of bytes)binary += String.fromCharCode(byte);
|
|
137
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
138
|
+
};
|
|
139
|
+
const randomString = (bytes = 32)=>base64Url(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
140
|
+
const pkceChallenge = async (verifier)=>base64Url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
|
|
141
|
+
const PLACEHOLDER_ORIGIN = 'https://site.invalid';
|
|
142
|
+
// Only a path on this site: never an open redirect. Resolved the way a
|
|
143
|
+
// browser reads Location, which drops tabs and newlines and reads \ as /.
|
|
144
|
+
const safeReturnTo = (value)=>{
|
|
145
|
+
if (!value?.startsWith('/')) return '/';
|
|
146
|
+
const url = new URL(value, PLACEHOLDER_ORIGIN);
|
|
147
|
+
return url.origin === PLACEHOLDER_ORIGIN ? `${url.pathname}${url.search}${url.hash}` : '/';
|
|
148
|
+
};
|
|
149
|
+
const normalizeBasePath = (basePath)=>`/${basePath.replace(/^\/+|\/+$/g, '')}`;
|
|
150
|
+
// The handler for everything under `basePath`. In Next.js:
|
|
151
|
+
//
|
|
152
|
+
// // app/cms/[...path]/route.ts
|
|
153
|
+
// const handler = createSiteEditing({
|
|
154
|
+
// spaceId: process.env.CONTENT_SPACE_ID!,
|
|
155
|
+
// environment: 'production',
|
|
156
|
+
// onSignIn: async () => (await draftMode()).enable(),
|
|
157
|
+
// onSignOut: async () => (await draftMode()).disable(),
|
|
158
|
+
// })
|
|
159
|
+
// export { handler as GET, handler as POST }
|
|
160
|
+
const createSiteEditing = ({ spaceId, environment, url, basePath = '/cms', siteUrl, onSignIn, onSignOut, timeout = DEFAULT_TIMEOUT, fetch: fetchImpl })=>{
|
|
161
|
+
const cms = normalizeUrl(url || DEFAULT_URL);
|
|
162
|
+
const base = normalizeBasePath(basePath);
|
|
163
|
+
const doFetch = fetchImpl ?? ((...args)=>fetch(...args));
|
|
164
|
+
const callCms = (path, init = {})=>doFetch(`${cms}${SITE_PATH}/${path}`, {
|
|
165
|
+
...init,
|
|
166
|
+
redirect: 'manual',
|
|
167
|
+
signal: AbortSignal.timeout(timeout)
|
|
168
|
+
});
|
|
169
|
+
return async (request)=>{
|
|
170
|
+
const requestUrl = new URL(request.url);
|
|
171
|
+
const origin = siteUrl ? normalizeUrl(siteUrl) : requestUrl.origin;
|
|
172
|
+
const secure = origin.startsWith('https:');
|
|
173
|
+
const redirectUri = `${origin}${base}/callback`;
|
|
174
|
+
const cookies = parseCookies(request.headers.get('cookie') ?? '');
|
|
175
|
+
const path = requestUrl.pathname.startsWith(`${base}/`) ? requestUrl.pathname.slice(base.length + 1) : null;
|
|
176
|
+
const sessionCookies = (session)=>[
|
|
177
|
+
serializeCookie(SITE_TOKEN_COOKIE, session.token, {
|
|
178
|
+
maxAge: session.maxAge,
|
|
179
|
+
path: '/',
|
|
180
|
+
httpOnly: true,
|
|
181
|
+
secure
|
|
182
|
+
}),
|
|
183
|
+
serializeCookie(SITE_EDITING_COOKIE, session.token ? base : '', {
|
|
184
|
+
maxAge: session.maxAge,
|
|
185
|
+
path: '/',
|
|
186
|
+
httpOnly: false,
|
|
187
|
+
secure
|
|
188
|
+
})
|
|
189
|
+
];
|
|
190
|
+
const clearedCookies = ()=>sessionCookies({
|
|
191
|
+
token: '',
|
|
192
|
+
maxAge: 0
|
|
193
|
+
});
|
|
194
|
+
const redirect = (location, setCookies = [])=>{
|
|
195
|
+
const headers = new Headers({
|
|
196
|
+
Location: location,
|
|
197
|
+
'Cache-Control': 'no-store'
|
|
198
|
+
});
|
|
199
|
+
for (const cookie of setCookies)headers.append('Set-Cookie', cookie);
|
|
200
|
+
return new Response(null, {
|
|
201
|
+
status: 302,
|
|
202
|
+
headers
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
if (path === 'login' && request.method === 'GET') {
|
|
206
|
+
const state = randomString(16);
|
|
207
|
+
const verifier = randomString(48);
|
|
208
|
+
const flow = JSON.stringify({
|
|
209
|
+
state,
|
|
210
|
+
verifier,
|
|
211
|
+
returnTo: safeReturnTo(requestUrl.searchParams.get('return_to'))
|
|
212
|
+
});
|
|
213
|
+
const connect = new URL(`${cms}/site/connect`);
|
|
214
|
+
connect.search = new URLSearchParams({
|
|
215
|
+
space: spaceId,
|
|
216
|
+
environment,
|
|
217
|
+
redirect_uri: redirectUri,
|
|
218
|
+
state,
|
|
219
|
+
code_challenge: await pkceChallenge(verifier),
|
|
220
|
+
code_challenge_method: 'S256'
|
|
221
|
+
}).toString();
|
|
222
|
+
return redirect(connect.toString(), [
|
|
223
|
+
serializeCookie(FLOW_COOKIE, flow, {
|
|
224
|
+
maxAge: FLOW_MAX_AGE,
|
|
225
|
+
path: base,
|
|
226
|
+
httpOnly: true,
|
|
227
|
+
secure
|
|
228
|
+
})
|
|
229
|
+
]);
|
|
230
|
+
}
|
|
231
|
+
if (path === 'callback' && request.method === 'GET') {
|
|
232
|
+
const clearFlow = serializeCookie(FLOW_COOKIE, '', {
|
|
233
|
+
maxAge: 0,
|
|
234
|
+
path: base,
|
|
235
|
+
httpOnly: true,
|
|
236
|
+
secure
|
|
237
|
+
});
|
|
238
|
+
let flow;
|
|
239
|
+
try {
|
|
240
|
+
flow = JSON.parse(cookies.get(FLOW_COOKIE) ?? '');
|
|
241
|
+
} catch {
|
|
242
|
+
flow = {};
|
|
243
|
+
}
|
|
244
|
+
const code = requestUrl.searchParams.get('code');
|
|
245
|
+
if (!code || typeof flow.state !== 'string' || typeof flow.verifier !== 'string' || flow.state !== requestUrl.searchParams.get('state')) {
|
|
246
|
+
return textResponse(400, 'This sign-in link is invalid or expired. Start again from the login link.', [
|
|
247
|
+
clearFlow
|
|
248
|
+
]);
|
|
249
|
+
}
|
|
250
|
+
const response = await callCms('token', {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: {
|
|
253
|
+
'Content-Type': 'application/json'
|
|
254
|
+
},
|
|
255
|
+
body: JSON.stringify({
|
|
256
|
+
code,
|
|
257
|
+
code_verifier: flow.verifier,
|
|
258
|
+
redirect_uri: redirectUri
|
|
259
|
+
})
|
|
260
|
+
});
|
|
261
|
+
if (!response.ok) {
|
|
262
|
+
return textResponse(400, 'Obelism Content did not accept the sign-in. Start again from the login link.', [
|
|
263
|
+
clearFlow
|
|
264
|
+
]);
|
|
265
|
+
}
|
|
266
|
+
const session = await response.json();
|
|
267
|
+
await onSignIn?.(session);
|
|
268
|
+
const maxAge = (Date.parse(session.expiresAt) - Date.now()) / 1000;
|
|
269
|
+
return redirect(safeReturnTo(flow.returnTo), [
|
|
270
|
+
clearFlow,
|
|
271
|
+
...sessionCookies({
|
|
272
|
+
token: session.token,
|
|
273
|
+
maxAge
|
|
274
|
+
})
|
|
275
|
+
]);
|
|
276
|
+
}
|
|
277
|
+
if (path === 'logout') {
|
|
278
|
+
const token = cookies.get(SITE_TOKEN_COOKIE);
|
|
279
|
+
if (token) {
|
|
280
|
+
await callCms('session', {
|
|
281
|
+
method: 'DELETE',
|
|
282
|
+
headers: {
|
|
283
|
+
Authorization: `Bearer ${token}`
|
|
284
|
+
}
|
|
285
|
+
}).catch(()=>null);
|
|
286
|
+
}
|
|
287
|
+
await onSignOut?.();
|
|
288
|
+
return redirect(safeReturnTo(requestUrl.searchParams.get('return_to')), clearedCookies());
|
|
289
|
+
}
|
|
290
|
+
if (path?.startsWith('api/')) {
|
|
291
|
+
const route = path.slice('api/'.length);
|
|
292
|
+
if (!siteApiAllows(request.method, route)) {
|
|
293
|
+
return Response.json({
|
|
294
|
+
error: 'Not found'
|
|
295
|
+
}, {
|
|
296
|
+
status: 404
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
if (request.method !== 'GET' && request.headers.get(SITE_REQUEST_HEADER) !== '1') {
|
|
300
|
+
return Response.json({
|
|
301
|
+
error: 'Forbidden'
|
|
302
|
+
}, {
|
|
303
|
+
status: 403
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
const token = cookies.get(SITE_TOKEN_COOKIE);
|
|
307
|
+
if (!token) {
|
|
308
|
+
return Response.json({
|
|
309
|
+
error: 'Not signed in'
|
|
310
|
+
}, {
|
|
311
|
+
status: 401
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
const response = await callCms(route, {
|
|
315
|
+
method: request.method,
|
|
316
|
+
headers: {
|
|
317
|
+
Authorization: `Bearer ${token}`,
|
|
318
|
+
...request.method !== 'GET' && {
|
|
319
|
+
'Content-Type': 'application/json'
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
...request.method !== 'GET' && {
|
|
323
|
+
body: await request.text()
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
const headers = new Headers({
|
|
327
|
+
'Content-Type': 'application/json',
|
|
328
|
+
'Cache-Control': 'no-store'
|
|
329
|
+
});
|
|
330
|
+
// The session ended in the CMS: stop showing the editing UI.
|
|
331
|
+
if (response.status === 401) {
|
|
332
|
+
for (const cookie of clearedCookies()){
|
|
333
|
+
headers.append('Set-Cookie', cookie);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return new Response(await response.text(), {
|
|
337
|
+
status: response.status,
|
|
338
|
+
headers
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
return Response.json({
|
|
342
|
+
error: 'Not found'
|
|
343
|
+
}, {
|
|
344
|
+
status: 404
|
|
345
|
+
});
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
const textResponse = (status, text, setCookies)=>{
|
|
349
|
+
const headers = new Headers({
|
|
350
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
351
|
+
'Cache-Control': 'no-store'
|
|
352
|
+
});
|
|
353
|
+
for (const cookie of setCookies)headers.append('Set-Cookie', cookie);
|
|
354
|
+
return new Response(text, {
|
|
355
|
+
status,
|
|
356
|
+
headers
|
|
357
|
+
});
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
export { SITE_EDITING_COOKIE as S, SITE_REQUEST_HEADER as a, SITE_TOKEN_COOKIE as b, createSiteEditing as c, pkceChallenge as d, safeReturnTo as e, parseCookies as p, readSiteToken as r, siteApi as s };
|