@botiverse/porthole 0.5.1 → 0.7.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/README.md +41 -0
- package/dist/bridge/bridge.d.ts +13 -0
- package/dist/bridge/bridge.js +208 -13
- package/dist/bridge/navigation.d.ts +1 -6
- package/dist/bridge/navigation.js +11 -0
- package/dist/bridge/refusal.d.ts +5 -1
- package/dist/bridge/refusal.js +16 -0
- package/dist/bridge/types.d.ts +41 -4
- package/dist/check/check.d.ts +19 -3
- package/dist/check/check.js +55 -8
- package/dist/check/files.d.ts +26 -0
- package/dist/check/files.js +307 -0
- package/dist/check/instrument.d.ts +3 -0
- package/dist/check/lint.js +31 -12
- package/dist/check/page-source.js +1 -1
- package/dist/check/page.js +14 -0
- package/dist/check/tools.d.ts +23 -0
- package/dist/check/tools.js +27 -3
- package/dist/compile/policy.d.ts +34 -0
- package/dist/compile/policy.js +74 -0
- package/dist/config/capabilities.d.ts +62 -3
- package/dist/config/capabilities.js +20 -0
- package/dist/config/schema.d.ts +32 -0
- package/dist/config/validate.d.ts +1 -1
- package/dist/config/validate.js +74 -5
- package/dist/conformance/harness-source.js +1 -1
- package/dist/conformance/index.d.ts +1 -0
- package/dist/conformance/index.js +2 -0
- package/dist/conformance/runtime.d.ts +58 -0
- package/dist/conformance/runtime.js +314 -0
- package/dist/files/paths.d.ts +99 -0
- package/dist/files/paths.js +263 -0
- package/dist/files/types.d.ts +24 -0
- package/dist/files/types.js +83 -0
- package/dist/guide/gates.d.ts +3 -0
- package/dist/guide/gates.js +19 -0
- package/dist/guide/guide.d.ts +2 -0
- package/dist/guide/guide.js +44 -32
- package/dist/guide/limits.js +4 -4
- package/dist/guide/runtime.d.ts +13 -0
- package/dist/guide/runtime.js +202 -0
- package/dist/host/create-host.js +45 -0
- package/dist/host/locate.js +8 -0
- package/dist/host/locator.js +7 -0
- package/dist/host/types.d.ts +18 -0
- package/dist/index.d.ts +13 -4
- package/dist/index.js +16 -3
- package/dist/isolation/types.d.ts +8 -0
- package/dist/presets/presets.d.ts +6 -0
- package/dist/presets/presets.js +1 -0
- package/dist/protocol/adapter.d.ts +4 -0
- package/dist/protocol/mcp-apps.d.ts +6 -0
- package/dist/protocol/mcp-apps.js +6 -0
- package/dist/protocol/runtime-calls.d.ts +28 -0
- package/dist/protocol/runtime-calls.js +113 -0
- package/dist/protocol/shell-adapter.js +52 -3
- package/dist/react/dialog.js +31 -0
- package/dist/react/frame.d.ts +13 -0
- package/dist/react/frame.js +6 -0
- package/dist/runtime/contract.d.ts +193 -0
- package/dist/runtime/contract.js +216 -0
- package/dist/runtime/db.d.ts +153 -0
- package/dist/runtime/db.js +398 -0
- package/dist/runtime/declaration.d.ts +86 -0
- package/dist/runtime/declaration.js +266 -0
- package/dist/runtime/levels.d.ts +33 -0
- package/dist/runtime/levels.js +41 -0
- package/dist/runtime/requests.d.ts +125 -0
- package/dist/runtime/requests.js +199 -0
- package/dist/runtime/segments.d.ts +8 -0
- package/dist/runtime/segments.js +14 -0
- package/dist/runtime/types.generated.d.ts +1 -0
- package/dist/runtime/types.generated.js +19 -0
- package/dist/server/files.d.ts +57 -0
- package/dist/server/files.js +338 -0
- package/dist/server/host.d.ts +44 -2
- package/dist/server/host.js +42 -2
- package/dist/server/index.d.ts +5 -2
- package/dist/server/index.js +5 -1
- package/dist/server/keys.d.ts +8 -0
- package/dist/server/keys.js +34 -0
- package/dist/server/pseudonym.d.ts +9 -0
- package/dist/server/pseudonym.js +20 -0
- package/dist/server/server.d.ts +0 -5
- package/dist/server/server.js +468 -24
- package/dist/server/types.d.ts +118 -5
- package/dist/shell/document.d.ts +27 -0
- package/dist/shell/document.js +46 -2
- package/dist/shell/legacy.d.ts +21 -0
- package/dist/shell/legacy.js +63 -0
- package/dist/shell/plan.d.ts +17 -1
- package/dist/shell/plan.js +13 -2
- package/dist/shell/runtime.d.ts +2 -1
- package/dist/shell/runtime.js +114 -46
- package/dist/shell/use.d.ts +15 -0
- package/dist/shell/use.js +235 -0
- package/docs/ADOPTING.md +142 -5
- package/docs/ARCHITECTURE.md +34 -5
- package/docs/DECISIONS.md +716 -7
- package/docs/DESIGN.md +97 -3
- package/package.json +3 -1
- package/src/bridge/bridge.ts +281 -17
- package/src/bridge/navigation.ts +12 -0
- package/src/bridge/refusal.ts +16 -0
- package/src/bridge/types.ts +46 -4
- package/src/check/check.ts +100 -14
- package/src/check/files.ts +384 -0
- package/src/check/instrument.ts +3 -0
- package/src/check/lint.ts +33 -12
- package/src/check/page.ts +14 -0
- package/src/check/tools.ts +52 -3
- package/src/compile/policy.ts +92 -0
- package/src/config/capabilities.ts +49 -2
- package/src/config/schema.ts +32 -0
- package/src/config/validate.ts +107 -5
- package/src/conformance/index.ts +7 -0
- package/src/conformance/runtime.ts +573 -0
- package/src/files/paths.ts +323 -0
- package/src/files/types.ts +101 -0
- package/src/guide/gates.ts +25 -0
- package/src/guide/guide.ts +78 -52
- package/src/guide/limits.ts +4 -4
- package/src/guide/runtime.ts +244 -0
- package/src/host/create-host.ts +55 -0
- package/src/host/locate.ts +10 -0
- package/src/host/locator.ts +11 -0
- package/src/host/types.ts +18 -0
- package/src/index.ts +121 -0
- package/src/isolation/types.ts +8 -0
- package/src/presets/presets.ts +7 -0
- package/src/protocol/adapter.ts +3 -1
- package/src/protocol/mcp-apps.ts +7 -0
- package/src/protocol/runtime-calls.ts +138 -0
- package/src/protocol/shell-adapter.ts +56 -2
- package/src/react/dialog.tsx +33 -0
- package/src/react/frame.tsx +19 -0
- package/src/runtime/contract.ts +305 -0
- package/src/runtime/db.ts +530 -0
- package/src/runtime/declaration.ts +378 -0
- package/src/runtime/levels.ts +69 -0
- package/src/runtime/requests.ts +339 -0
- package/src/runtime/segments.ts +17 -0
- package/src/runtime/types.generated.ts +19 -0
- package/src/server/files.ts +425 -0
- package/src/server/host.ts +84 -3
- package/src/server/index.ts +22 -0
- package/src/server/keys.ts +53 -0
- package/src/server/pseudonym.ts +21 -0
- package/src/server/server.ts +565 -26
- package/src/server/types.ts +124 -4
- package/src/shell/document.ts +74 -4
- package/src/shell/legacy.ts +64 -0
- package/src/shell/plan.ts +37 -3
- package/src/shell/runtime.ts +114 -46
- package/src/shell/use.ts +235 -0
- package/types/runtime/v1/artifact.d.ts +50 -0
- package/types/runtime/v1/assets.d.ts +43 -0
- package/types/runtime/v1/chat.d.ts +13 -0
- package/types/runtime/v1/clipboard.d.ts +14 -0
- package/types/runtime/v1/comments.d.ts +24 -0
- package/types/runtime/v1/context.d.ts +16 -0
- package/types/runtime/v1/data.d.ts +29 -0
- package/types/runtime/v1/db.d.ts +110 -0
- package/types/runtime/v1/downloads.d.ts +22 -0
- package/types/runtime/v1/links.d.ts +13 -0
- package/types/runtime/v1/porthole.d.ts +44 -0
- package/types/runtime/v1/user.d.ts +19 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** A db path's segment (P088): letters, digits and `_ . ~ : @ + -`, at most 128. */
|
|
2
|
+
export const SEGMENT = /^[A-Za-z0-9_.~:@+-]{1,128}$/u;
|
|
3
|
+
/**
|
|
4
|
+
* Whether `value` is one path segment: what a viewer's id must be to name their own data
|
|
5
|
+
* (`data/users/<id>`), and never `me`, which names them (after the review: an id `a/b` would
|
|
6
|
+
* reach another person's tree).
|
|
7
|
+
*/
|
|
8
|
+
export function isDbSegment(value) {
|
|
9
|
+
return (typeof value === "string" &&
|
|
10
|
+
SEGMENT.test(value) &&
|
|
11
|
+
value !== "." &&
|
|
12
|
+
value !== ".." &&
|
|
13
|
+
value !== "me");
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const RUNTIME_TYPES: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Generated by scripts/runtime-types.ts from types/runtime (P085): do not edit.
|
|
2
|
+
// Each runtime contract's type definitions, by version and capability (`porthole` is the call
|
|
3
|
+
// contract every capability shares).
|
|
4
|
+
export const RUNTIME_TYPES = {
|
|
5
|
+
"1": {
|
|
6
|
+
"artifact": "// Porthole capability runtime, contract 1: artifact (this artifact itself). Declare it: { artifact: {} }.\n// Use it when the page is the record: a checklist, a plan, a document someone edits in place.\n\ninterface PortholeArtifactFile {\n readonly path: string;\n readonly size: number;\n readonly sha256: string;\n}\n\ninterface PortholeArtifactVersion {\n /** The version's id: what a publish names as its base. */\n readonly version: string;\n readonly number?: number;\n /** The page it opens at (\"index.html\"). */\n readonly entry: string;\n readonly files: readonly PortholeArtifactFile[];\n}\n\ninterface PortholeArtifactPublish {\n /** The version you read and changed (from get()). If it moved, publish rejects with conflict. */\n readonly base: string;\n /**\n * A patch on base's files, by path: text, bytes (a Blob, an ArrayBuffer, a typed array), or\n * null to remove one; files not named are kept. A page sends its whole document, as it should\n * be served. At most 255 files.\n */\n readonly files: Readonly<Record<string, string | Blob | ArrayBuffer | ArrayBufferView | null>>;\n readonly entry?: string;\n /** At most 60 characters. */\n readonly label?: string;\n /** At most 500 characters. */\n readonly note?: string;\n}\n\ninterface PortholeArtifact {\n /** The current version and its files (fetch a file by its relative path). Level: view. */\n get(): Promise<PortholeArtifactVersion>;\n /**\n * Publishes a new version of this artifact, from a click; the app asks the person first. The\n * page can't change what it declares. On conflict: get() again, merge, publish again. Level:\n * admin.\n */\n publish(\n change: PortholeArtifactPublish,\n ): Promise<{ readonly version: string; readonly number?: number }>;\n}\n\ninterface PortholeCapabilities {\n artifact: PortholeArtifact;\n}\n",
|
|
7
|
+
"assets": "// Porthole capability runtime, contract 1: assets (the artifact's asset library). Declare it: { assets: {} }.\n// Assets live outside every version, at \"/_blob/<id>\" on the page's own origin: keep that url (or\n// the id) in your data, and show it with assets.url(id). Images, media and fonts load; scripts and\n// stylesheets only where the app lets only admins upload, and only those an admin added. Not for\n// files that version with the page: publish those with it.\n\ninterface PortholeAsset {\n /** 32 hex characters. */\n readonly id: string;\n /** \"/_blob/<id>\": use it as given. */\n readonly url: string;\n readonly name: string;\n /** Porthole's type for the name's extension. */\n readonly type: string;\n readonly size: number;\n}\n\ninterface PortholeAssets {\n /** The library, people's uploads through the page included. Level: view. */\n list(): Promise<readonly PortholeAsset[]>;\n /**\n * Adds a file (a File from an <input type=\"file\">, a Blob, bytes) under its name (a File's own,\n * or options.name): an image, media, a font, a PDF, text or data, never HTML; a script or a\n * stylesheet only where uploads are the admins'. The app may ask the person first. Level: admin,\n * unless the app lets people who interact upload.\n */\n upload(\n file: Blob | ArrayBuffer | ArrayBufferView,\n options?: { readonly name?: string },\n ): Promise<PortholeAsset>;\n /**\n * The address that loads an asset in this page now: put it in src or href when you show it.\n * Store the id (or \"/_blob/<id>\"), never this: it carries this page's access. A \"/_blob/<id>\"\n * written in the page loads too, except in some browsers' frames (Safari's); this always does.\n */\n url(id: string): string;\n /** Removes one, from a click; the app asks the person first. Level: admin. */\n delete(id: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n assets: PortholeAssets;\n}\n",
|
|
8
|
+
"chat": "// Porthole capability runtime, contract 1: chat. Declare it: { chat: {} }.\n\ninterface PortholeChat {\n /**\n * Sends text to the agent as the person's message (\"explain this point\"). Call it from a click.\n * Resolves true if it was sent. Level: interact.\n */\n send(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n chat: PortholeChat;\n}\n",
|
|
9
|
+
"clipboard": "// Porthole capability runtime, contract 1: clipboard. Built in: never declare it.\n\ninterface PortholeClipboard {\n /**\n * Copies text to the person's clipboard (at most 20,000 characters); the app shows them what\n * was copied. Nothing else in the page can write the clipboard. Call it from a click.\n * Resolves true if it was copied. Level: view.\n */\n copy(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n clipboard: PortholeClipboard;\n}\n",
|
|
10
|
+
"comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000). */\n readonly quote?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }). The person writes\n * and posts it in the app. Resolves true if the composer opened. Write-only: a page never reads\n * comments. Call it from a click. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
|
|
11
|
+
"context": "// Porthole capability runtime, contract 1: context. Declare it: { context: {} }.\n\ninterface PortholeContextUpdate {\n /** MCP content blocks: [{ type: \"text\", text: \"…\" }]. */\n readonly content?: readonly unknown[];\n readonly structuredContent?: Record<string, unknown>;\n}\n\ninterface PortholeContext {\n /** Tells the agent what the person is looking at, for its next turns (replaces the last). Level: interact. */\n set(update: PortholeContextUpdate): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n context: PortholeContext;\n}\n",
|
|
12
|
+
"data": "// Porthole capability runtime, contract 1: data (the app's data and tools).\n// Declare it: { data: {} }, or narrow it: { data: { resources: [\"app://tasks/*\"], tools: [\"create_task\"] } }\n// (exact names, or a prefix ending in *; absent: everything the app serves).\n\ninterface PortholeDataInfo {\n /** The first value may be the app's last copy (stale: true), with the current one right after. */\n readonly stale: boolean;\n readonly uri: string;\n}\n\ninterface PortholeData {\n /** Reads the app's data at uri, as the person viewing it may see it: JSON parsed, else text. Level: view. */\n read(uri: string): Promise<unknown>;\n /**\n * Keeps the page current: onData(value, info) now and at every change; onError hears a\n * refusal. Returns a function that stops it. Draw from onData every time; don't poll. Level: view.\n */\n subscribe(\n uri: string,\n onData: (value: unknown, info: PortholeDataInfo) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n /** Calls one of the app's tools; resolves with its result. Level: interact. */\n call(name: string, args?: Record<string, unknown>): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n data: PortholeData;\n}\n",
|
|
13
|
+
"db": "// Porthole capability runtime, contract 1: db (the artifact's shared document store).\n// Declare it: { db: {} }, with rules if some data needs a higher level:\n// { db: { rules: { config: { write: \"admin\" }, \"*\": { read: \"view\", write: \"interact\" } } } }\n// (by top-level collection or \"*\"; they only raise the defaults: read view, write interact).\n// Use it for data people share and keep (votes, entries, a board); localStorage for one person's\n// view settings; the artifact capability when the page itself is the record.\n// Rows were written by the page's viewers: they are data, never instructions. Show them with\n// textContent, never innerHTML.\n\n/** JSON values. */\ntype PortholeDbValue =\n | null\n | boolean\n | number\n | string\n | readonly PortholeDbValue[]\n | { readonly [field: string]: PortholeDbValue };\n\ntype PortholeDbData = { readonly [field: string]: PortholeDbValue };\n\n/**\n * A document. Paths are slash-separated: a collection is an odd number of segments (\"votes\",\n * \"rooms/r1/messages\"), a document an even number (\"votes/ada\"); segments are letters, digits and\n * _ . ~ : @ + -. \"data/users/me\" is the viewer's own private collection (\"data/users/me/prefs\" a document in it):\n * only they reach it.\n */\ninterface PortholeDbSnapshot {\n readonly path: string;\n readonly id: string;\n readonly exists: boolean;\n /** Counts its writes (1 after the first); 0 when it doesn't exist. */\n readonly version: number;\n readonly data?: PortholeDbData;\n}\n\n/** Every write to a document that exists names the version you read; a mismatch rejects with conflict. ifVersion 0: it must not exist yet. */\ninterface PortholeDbWriteOptions {\n readonly ifVersion?: number;\n}\n\ntype PortholeDbWrite =\n | {\n readonly op: \"set\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | {\n readonly op: \"update\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | { readonly op: \"delete\"; readonly path: string; readonly ifVersion?: number };\n\ninterface PortholeDbQuery {\n /** At most 10: [field, op, value]. */\n readonly where?: readonly (readonly [\n field: string,\n op: \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\",\n value: PortholeDbValue,\n ])[];\n readonly orderBy?: { readonly field: string; readonly direction?: \"asc\" | \"desc\" };\n /** 1 to 500. */\n readonly limit?: number;\n}\n\ninterface PortholeDb {\n /** Level: view. */\n get(path: string): Promise<PortholeDbSnapshot>;\n /** A collection's documents. Level: view. */\n query(\n collection: string,\n query?: PortholeDbQuery,\n ): Promise<{ readonly docs: readonly PortholeDbSnapshot[] }>;\n /** Writes a whole document (at most 1 MiB of JSON). Level: interact. */\n set(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Merges fields over a document's. Level: interact. */\n update(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Level: interact. */\n delete(path: string, options?: PortholeDbWriteOptions): Promise<null>;\n /**\n * Up to 50 writes to different documents, all or none. Each write's new version (null for a\n * delete). Each write at its own level.\n */\n batch(\n writes: readonly PortholeDbWrite[],\n ): Promise<{ readonly versions: readonly (number | null)[] }>;\n /**\n * Follows a document (a snapshot) or a collection ({ docs }) now and at every change. Returns a\n * function that stops it. Draw from onData; don't poll. Level: view.\n */\n onSnapshot(\n path: string,\n onData: (state: PortholeDbSnapshot | { readonly docs: readonly PortholeDbSnapshot[] }) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n}\n\ninterface PortholeCapabilities {\n db: PortholeDb;\n}\n",
|
|
14
|
+
"downloads": "// Porthole capability runtime, contract 1: downloads. Built in: never declare it.\n\n/** A file to hand the person: its name, and its text or bytes. */\ninterface PortholeDownload {\n /** A file name, no slashes: \"report.csv\". Its extension gives its type unless `type` says. */\n readonly name: string;\n readonly type?: string;\n readonly text?: string;\n readonly data?: Blob | ArrayBuffer | ArrayBufferView;\n}\n\ninterface PortholeDownloads {\n /**\n * Hands the person a file to save (<a download> and script-driven saves don't work here).\n * Call it from a click. Resolves true if the download started. Level: view.\n */\n save(file: PortholeDownload): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n downloads: PortholeDownloads;\n}\n",
|
|
15
|
+
"links": "// Porthole capability runtime, contract 1: links. Built in: never declare it.\n\ninterface PortholeLinks {\n /**\n * Opens an http(s) link outside the page (a click on an <a href> does the same). Call it from\n * a click. Resolves true if it opened. Level: view.\n */\n open(url: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n links: PortholeLinks;\n}\n",
|
|
16
|
+
"porthole": "// Porthole capability runtime, contract 1: the call contract (how a page reaches any capability).\n\n/**\n * Why a call was refused: branch on it; show `message` (a sentence for the person) where the\n * result would be. Never retry in a loop.\n * - consent_required: the person hasn't allowed it yet.\n * - denied: the person said no.\n * - rate_limited: too many calls this minute.\n * - not_allowed: not available here (some places show the page without it).\n * - failed: the app tried and couldn't.\n * - forbidden: this person may see the page but not do this (their level).\n * - conflict: what you change moved since you read it: read it again, then write.\n * - too_large: past a limit.\n */\ntype PortholeErrorCode =\n | \"consent_required\"\n | \"denied\"\n | \"rate_limited\"\n | \"not_allowed\"\n | \"failed\"\n | \"forbidden\"\n | \"conflict\"\n | \"too_large\";\n\n/** What every capability method rejects with. */\ninterface PortholeError extends Error {\n readonly code: PortholeErrorCode;\n}\n\n/** Each capability's namespace, by the name `use` takes (each capability's own file adds its own). */\ninterface PortholeCapabilities {}\n\ninterface PortholeRuntime {\n /**\n * The capability's namespace, frozen; or null when it isn't there for this page: the app\n * doesn't offer it, the page didn't declare it, or no app is showing the page (a tab, a\n * preview). The reasons are indistinguishable: draw the page without it. `use` never rejects;\n * permission problems come when you call a method (a rejected promise, `PortholeError`).\n */\n use<N extends keyof PortholeCapabilities>(name: N): Promise<PortholeCapabilities[N] | null>;\n}\n\n/** The page's one global. Nothing else is added to `window`. */\ndeclare const porthole: PortholeRuntime;\n",
|
|
17
|
+
"user": "// Porthole capability runtime, contract 1: user. Declare it: { user: {} }.\n\n/** Who is viewing, as the app says. */\ninterface PortholeUserInfo {\n /** The app's id for this person (whose data \"data/users/me\" is), or null if it gives none. */\n readonly id: string | null;\n readonly name: string | null;\n /** What they may do here: view < interact < admin < owner. */\n readonly level: \"view\" | \"interact\" | \"admin\" | \"owner\";\n}\n\ninterface PortholeUser {\n /** Level: view. */\n get(): Promise<PortholeUserInfo>;\n}\n\ninterface PortholeCapabilities {\n user: PortholeUser;\n}\n",
|
|
18
|
+
},
|
|
19
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { CompiledConfig } from "../compile/compile.ts";
|
|
2
|
+
import type { StoredAsset, StoredFiles } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Serving a version made of files (P081, P082): each path looked up in its manifest only, each
|
|
5
|
+
* answer typed by Porthole's table, with `nosniff`, its CSP in a header, its cache rule and a
|
|
6
|
+
* strong ETag; pages in the shell, ranges for the rest.
|
|
7
|
+
*/
|
|
8
|
+
export interface FileServing {
|
|
9
|
+
readonly request: Request;
|
|
10
|
+
readonly set: StoredFiles;
|
|
11
|
+
/** The request's path below the base, as the URL has it (percent-encoded). */
|
|
12
|
+
readonly rest: string;
|
|
13
|
+
/** The search part, kept on a redirect. */
|
|
14
|
+
readonly search: string;
|
|
15
|
+
/** The version's own address on its origin: a path ending in `/`. */
|
|
16
|
+
readonly base: string;
|
|
17
|
+
readonly origin: string;
|
|
18
|
+
/**
|
|
19
|
+
* Whether `base` names this version and no other (a pinned address, a frame's): its files are
|
|
20
|
+
* immutable there. Else they are revalidated (an address that may mean another version later).
|
|
21
|
+
*/
|
|
22
|
+
readonly pinned: boolean;
|
|
23
|
+
/** The CSP source the version's files load from (P082): its path on the origin. */
|
|
24
|
+
readonly source: string;
|
|
25
|
+
readonly compiled: CompiledConfig;
|
|
26
|
+
readonly hostOrigins: readonly string[];
|
|
27
|
+
readonly frameAncestors: string;
|
|
28
|
+
/**
|
|
29
|
+
* A ticket's answer (P083): the entry, served at the ticket's address, never stored; its shell
|
|
30
|
+
* moves the frame to the entry's own address under `base` before anything loads, and renews
|
|
31
|
+
* that address before it ends (`expires`, epoch ms).
|
|
32
|
+
*/
|
|
33
|
+
readonly ticket?: {
|
|
34
|
+
readonly expires: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Whether the request is a page loading (a navigation), not a subresource. */
|
|
38
|
+
export declare function isNavigation(request: Request): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the request is a running page's own load: from its own origin (`Sec-Fetch-Site`, which
|
|
41
|
+
* only a browser sets and no page can change), and not a navigation.
|
|
42
|
+
*/
|
|
43
|
+
export declare const ownLoad: (request: Request) => boolean;
|
|
44
|
+
export declare function serveFile(serving: FileServing): Promise<Response>;
|
|
45
|
+
/**
|
|
46
|
+
* An asset of an artifact's library (P089), at `/_blob/<id>`: typed by Porthole's table by its
|
|
47
|
+
* name, never as a page (one named so goes as a download), inert opened on its own (an SVG runs
|
|
48
|
+
* nothing), `nosniff`, loaded only by its own origin's pages (CORP), immutable (an id never names
|
|
49
|
+
* other bytes), its sha256 the ETag, ranges for media.
|
|
50
|
+
*/
|
|
51
|
+
export declare function serveAsset(serving: {
|
|
52
|
+
readonly request: Request;
|
|
53
|
+
readonly asset: StoredAsset;
|
|
54
|
+
readonly frameAncestors: string;
|
|
55
|
+
/** Whether a code-typed asset is served as code (trusted, where uploaded code runs). */
|
|
56
|
+
readonly code: boolean;
|
|
57
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { assetCspDirectives, fileSetCspDirectives, INERT_FILE_CSP, serializeCsp, } from "../compile/policy.js";
|
|
2
|
+
import { DEFAULT_ENTRY, lookupFile, requestFilePath } from "../files/paths.js";
|
|
3
|
+
import { fileTypeOf } from "../files/types.js";
|
|
4
|
+
import { isCodeAsset } from "../runtime/requests.js";
|
|
5
|
+
import { sha256, utf8 } from "./crypto.js";
|
|
6
|
+
const HEX = /^[0-9a-f]{64}$/u;
|
|
7
|
+
const YEAR = 31_536_000;
|
|
8
|
+
const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
9
|
+
/** A path's segments percent-encoded, for a `Location`. */
|
|
10
|
+
const encodePath = (path) => path
|
|
11
|
+
.split("/")
|
|
12
|
+
.map((segment) => encodeURIComponent(segment))
|
|
13
|
+
.join("/");
|
|
14
|
+
/** Whether the request is a page loading (a navigation), not a subresource. */
|
|
15
|
+
export function isNavigation(request) {
|
|
16
|
+
const mode = request.headers.get("sec-fetch-mode");
|
|
17
|
+
const dest = request.headers.get("sec-fetch-dest");
|
|
18
|
+
if (mode !== null || dest !== null) {
|
|
19
|
+
return mode === "navigate" || dest === "document" || dest === "iframe" || dest === "frame";
|
|
20
|
+
}
|
|
21
|
+
return (request.headers.get("accept") ?? "").includes("text/html");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Whether the request is a running page's own load: from its own origin (`Sec-Fetch-Site`, which
|
|
25
|
+
* only a browser sets and no page can change), and not a navigation.
|
|
26
|
+
*/
|
|
27
|
+
export const ownLoad = (request) => request.headers.get("sec-fetch-site") === "same-origin" && !isNavigation(request);
|
|
28
|
+
/** Whether `If-None-Match` names this ETag. */
|
|
29
|
+
function notModified(request, etag) {
|
|
30
|
+
const asked = request.headers.get("if-none-match");
|
|
31
|
+
if (asked === null) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
return asked
|
|
35
|
+
.split(",")
|
|
36
|
+
.map((each) => each.trim().replace(/^W\//u, ""))
|
|
37
|
+
.some((each) => each === "*" || each === etag);
|
|
38
|
+
}
|
|
39
|
+
/** A single `bytes=` range of a body of `size` bytes: the range, "unsatisfiable", or null (ignore it). */
|
|
40
|
+
function rangeOf(header, size) {
|
|
41
|
+
if (header === null) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const match = /^bytes=(\d*)-(\d*)$/u.exec(header.trim());
|
|
45
|
+
if (match === null) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const [, from = "", to = ""] = match;
|
|
49
|
+
if (from === "" && to === "") {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
if (from === "") {
|
|
53
|
+
// The last `to` bytes.
|
|
54
|
+
const length = Number(to);
|
|
55
|
+
if (length === 0) {
|
|
56
|
+
return "unsatisfiable";
|
|
57
|
+
}
|
|
58
|
+
return size === 0 ? "unsatisfiable" : { start: Math.max(0, size - length), end: size - 1 };
|
|
59
|
+
}
|
|
60
|
+
const start = Number(from);
|
|
61
|
+
const end = to === "" ? size - 1 : Math.min(Number(to), size - 1);
|
|
62
|
+
if (!Number.isSafeInteger(start) || start >= size || end < start) {
|
|
63
|
+
return "unsatisfiable";
|
|
64
|
+
}
|
|
65
|
+
return { start, end };
|
|
66
|
+
}
|
|
67
|
+
/** `body` from byte `start` through `end`. */
|
|
68
|
+
function slice(body, start, end) {
|
|
69
|
+
if (body instanceof Uint8Array) {
|
|
70
|
+
return body.subarray(start, end + 1);
|
|
71
|
+
}
|
|
72
|
+
let offset = 0;
|
|
73
|
+
return body.pipeThrough(new TransformStream({
|
|
74
|
+
transform(chunk, controller) {
|
|
75
|
+
const from = Math.max(start - offset, 0);
|
|
76
|
+
const to = Math.min(end + 1 - offset, chunk.byteLength);
|
|
77
|
+
if (from < to) {
|
|
78
|
+
controller.enqueue(chunk.subarray(from, to));
|
|
79
|
+
}
|
|
80
|
+
offset += chunk.byteLength;
|
|
81
|
+
if (offset > end) {
|
|
82
|
+
controller.terminate();
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
async function textOf(body) {
|
|
88
|
+
if (body instanceof Uint8Array) {
|
|
89
|
+
return new TextDecoder().decode(body);
|
|
90
|
+
}
|
|
91
|
+
return new Response(body).text();
|
|
92
|
+
}
|
|
93
|
+
const asBody = (body) => body instanceof Uint8Array ? new Uint8Array(body) : body;
|
|
94
|
+
/** The answer for nothing found: plain, inert. */
|
|
95
|
+
function nothing(serving, status, method) {
|
|
96
|
+
const text = status === 404 ? "Not found" : status === 405 ? "Content here is only read" : "Not allowed";
|
|
97
|
+
return new Response(method === "HEAD" ? null : text, {
|
|
98
|
+
status,
|
|
99
|
+
headers: {
|
|
100
|
+
"content-type": "text/plain; charset=utf-8",
|
|
101
|
+
"content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${serving.frameAncestors}`,
|
|
102
|
+
"cache-control": "no-store",
|
|
103
|
+
"x-content-type-options": "nosniff",
|
|
104
|
+
"referrer-policy": "no-referrer",
|
|
105
|
+
"x-robots-tag": "noindex, nofollow",
|
|
106
|
+
...(status === 405 ? { allow: "GET, HEAD" } : {}),
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
export async function serveFile(serving) {
|
|
111
|
+
const { request, set } = serving;
|
|
112
|
+
const method = request.method.toUpperCase();
|
|
113
|
+
// No service worker, ever: one would answer this origin's requests with documents of its
|
|
114
|
+
// own making, outside the shell and its CSP (P081).
|
|
115
|
+
if (request.headers.get("service-worker") !== null ||
|
|
116
|
+
request.headers.get("sec-fetch-dest") === "serviceworker") {
|
|
117
|
+
return nothing(serving, 403, method);
|
|
118
|
+
}
|
|
119
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
120
|
+
return nothing(serving, 405, method);
|
|
121
|
+
}
|
|
122
|
+
const path = requestFilePath(serving.rest);
|
|
123
|
+
if (path === null) {
|
|
124
|
+
return nothing(serving, 404, method);
|
|
125
|
+
}
|
|
126
|
+
const has = (each) => Object.hasOwn(set.files, each);
|
|
127
|
+
const entryPath = set.entry ?? DEFAULT_ENTRY;
|
|
128
|
+
const found = serving.ticket !== undefined
|
|
129
|
+
? has(entryPath)
|
|
130
|
+
? { kind: "file", path: entryPath, status: 200 }
|
|
131
|
+
: { kind: "none" }
|
|
132
|
+
: lookupFile(has, path, {
|
|
133
|
+
...(set.entry === undefined ? {} : { entry: set.entry }),
|
|
134
|
+
...(set.spa === undefined ? {} : { spa: set.spa }),
|
|
135
|
+
navigation: isNavigation(request),
|
|
136
|
+
});
|
|
137
|
+
if (found.kind === "none") {
|
|
138
|
+
return nothing(serving, 404, method);
|
|
139
|
+
}
|
|
140
|
+
// The version's own address, as a URL writes it.
|
|
141
|
+
const base = new URL(serving.base, serving.origin).href;
|
|
142
|
+
if (found.kind === "redirect") {
|
|
143
|
+
return new Response(null, {
|
|
144
|
+
status: 307,
|
|
145
|
+
headers: {
|
|
146
|
+
location: `${base}${encodePath(found.to)}${serving.search}`,
|
|
147
|
+
"cache-control": "no-store",
|
|
148
|
+
"referrer-policy": "no-referrer",
|
|
149
|
+
"x-robots-tag": "noindex, nofollow",
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
const entry = set.files[found.path];
|
|
154
|
+
const body = entry === undefined ? null : await set.read(found.path);
|
|
155
|
+
if (entry === undefined || body === null) {
|
|
156
|
+
return nothing(serving, 404, method);
|
|
157
|
+
}
|
|
158
|
+
const { type, role } = fileTypeOf(found.path);
|
|
159
|
+
// In a frame, the version's files are at a sealed address (P083), which their own loads of the
|
|
160
|
+
// artifact's assets carry as their `Referer` (P091): to this origin only, never another.
|
|
161
|
+
const referrer = serving.base.startsWith("/__porthole/f/") &&
|
|
162
|
+
serving.compiled.config.capabilities.assets !== undefined
|
|
163
|
+
? "same-origin"
|
|
164
|
+
: "no-referrer";
|
|
165
|
+
// Its version's files (P082), and its artifact's assets where the config serves them (P089).
|
|
166
|
+
const frameCsp = serializeCsp(assetCspDirectives(serving.compiled.config, fileSetCspDirectives(serving.compiled.cspDirectives, serving.source), serving.origin));
|
|
167
|
+
const headers = new Headers({
|
|
168
|
+
"content-type": type,
|
|
169
|
+
"x-content-type-options": "nosniff",
|
|
170
|
+
"referrer-policy": referrer,
|
|
171
|
+
"x-robots-tag": "noindex, nofollow",
|
|
172
|
+
// A page and a script (a worker's policy is its script's) get the page's CSP; anything else
|
|
173
|
+
// runs nothing when opened on its own.
|
|
174
|
+
"content-security-policy": `${role === "file" ? INERT_FILE_CSP : frameCsp}; frame-ancestors ${serving.frameAncestors}`,
|
|
175
|
+
});
|
|
176
|
+
if (role === "page") {
|
|
177
|
+
// Every page of the set in the shell (P081): its hardening, its host functions, its theme.
|
|
178
|
+
const html = serving.compiled.shellDocument({
|
|
179
|
+
origins: serving.hostOrigins,
|
|
180
|
+
document: await textOf(body),
|
|
181
|
+
cspMeta: false,
|
|
182
|
+
...(referrer === "same-origin" ? { referrer } : {}),
|
|
183
|
+
files: {
|
|
184
|
+
base,
|
|
185
|
+
// At a ticket's address: the entry's own (its directory's, for an entry in one).
|
|
186
|
+
...(serving.ticket === undefined
|
|
187
|
+
? {}
|
|
188
|
+
: {
|
|
189
|
+
address: `${base}${found.path.includes("/") ? encodePath(found.path) : ""}`,
|
|
190
|
+
expires: serving.ticket.expires,
|
|
191
|
+
}),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
if (serving.ticket !== undefined) {
|
|
195
|
+
headers.set("cache-control", "no-store");
|
|
196
|
+
return new Response(method === "HEAD" ? null : html, { status: 200, headers });
|
|
197
|
+
}
|
|
198
|
+
const etag = `"${hex(sha256(utf8(html)))}"`;
|
|
199
|
+
headers.set("etag", etag);
|
|
200
|
+
// A page is asked again each time it loads, so the host's check runs on every navigation.
|
|
201
|
+
headers.set("cache-control", "private, no-cache");
|
|
202
|
+
if (found.status === 200 && notModified(request, etag)) {
|
|
203
|
+
return new Response(null, { status: 304, headers });
|
|
204
|
+
}
|
|
205
|
+
return new Response(method === "HEAD" ? null : html, { status: found.status, headers });
|
|
206
|
+
}
|
|
207
|
+
const size = body instanceof Uint8Array ? body.byteLength : entry.size;
|
|
208
|
+
const etag = HEX.test(entry.sha256) ? `"${entry.sha256}"` : null;
|
|
209
|
+
if (etag !== null) {
|
|
210
|
+
headers.set("etag", etag);
|
|
211
|
+
}
|
|
212
|
+
headers.set("cache-control", serving.pinned ? `private, max-age=${YEAR}, immutable` : "private, no-cache");
|
|
213
|
+
// Only this origin's own pages load it: no other content origin (a sibling, same-site without
|
|
214
|
+
// the public suffix list) can embed it with the viewer's cookie.
|
|
215
|
+
headers.set("cross-origin-resource-policy", "same-origin");
|
|
216
|
+
headers.set("accept-ranges", "bytes");
|
|
217
|
+
if (role === "file" && type === "application/octet-stream") {
|
|
218
|
+
headers.set("content-disposition", "attachment");
|
|
219
|
+
}
|
|
220
|
+
if (etag !== null && notModified(request, etag)) {
|
|
221
|
+
if (!(body instanceof Uint8Array)) {
|
|
222
|
+
await body.cancel();
|
|
223
|
+
}
|
|
224
|
+
return new Response(null, { status: 304, headers });
|
|
225
|
+
}
|
|
226
|
+
const range = found.status === 200 ? rangeOf(request.headers.get("range"), size) : null;
|
|
227
|
+
if (range === "unsatisfiable") {
|
|
228
|
+
if (!(body instanceof Uint8Array)) {
|
|
229
|
+
await body.cancel();
|
|
230
|
+
}
|
|
231
|
+
headers.set("content-range", `bytes */${size}`);
|
|
232
|
+
return new Response(null, { status: 416, headers });
|
|
233
|
+
}
|
|
234
|
+
if (range !== null) {
|
|
235
|
+
headers.set("content-range", `bytes ${range.start}-${range.end}/${size}`);
|
|
236
|
+
headers.set("content-length", String(range.end - range.start + 1));
|
|
237
|
+
if (method === "HEAD" && !(body instanceof Uint8Array)) {
|
|
238
|
+
await body.cancel();
|
|
239
|
+
}
|
|
240
|
+
return new Response(method === "HEAD" ? null : asBody(slice(body, range.start, range.end)), {
|
|
241
|
+
status: 206,
|
|
242
|
+
headers,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
// A stream's length is the manifest's word: said for HEAD, left to the transfer otherwise.
|
|
246
|
+
if (body instanceof Uint8Array || method === "HEAD") {
|
|
247
|
+
headers.set("content-length", String(size));
|
|
248
|
+
}
|
|
249
|
+
if (method === "HEAD" && !(body instanceof Uint8Array)) {
|
|
250
|
+
await body.cancel();
|
|
251
|
+
}
|
|
252
|
+
return new Response(method === "HEAD" ? null : asBody(body), { status: found.status, headers });
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* An asset of an artifact's library (P089), at `/_blob/<id>`: typed by Porthole's table by its
|
|
256
|
+
* name, never as a page (one named so goes as a download), inert opened on its own (an SVG runs
|
|
257
|
+
* nothing), `nosniff`, loaded only by its own origin's pages (CORP), immutable (an id never names
|
|
258
|
+
* other bytes), its sha256 the ETag, ranges for media.
|
|
259
|
+
*/
|
|
260
|
+
export async function serveAsset(serving) {
|
|
261
|
+
const { request, asset } = serving;
|
|
262
|
+
const method = request.method.toUpperCase();
|
|
263
|
+
const plain = (status) => new Response(method === "HEAD" ? null : status === 404 ? "Not found" : "Only read", {
|
|
264
|
+
status,
|
|
265
|
+
headers: {
|
|
266
|
+
"content-type": "text/plain; charset=utf-8",
|
|
267
|
+
"content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${serving.frameAncestors}`,
|
|
268
|
+
"cache-control": "no-store",
|
|
269
|
+
"x-content-type-options": "nosniff",
|
|
270
|
+
...(status === 405 ? { allow: "GET, HEAD" } : {}),
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
274
|
+
return plain(405);
|
|
275
|
+
}
|
|
276
|
+
const body = await asset.read();
|
|
277
|
+
if (body === null) {
|
|
278
|
+
return plain(404);
|
|
279
|
+
}
|
|
280
|
+
const typed = fileTypeOf(asset.name);
|
|
281
|
+
// Never a page: an asset is the library's, outside the shell (P089); code only where it was
|
|
282
|
+
// trusted when it was uploaded (after the review).
|
|
283
|
+
const type = typed.role === "page" || (isCodeAsset(asset.name) && !serving.code)
|
|
284
|
+
? "application/octet-stream"
|
|
285
|
+
: typed.type;
|
|
286
|
+
const headers = new Headers({
|
|
287
|
+
"content-type": type,
|
|
288
|
+
"x-content-type-options": "nosniff",
|
|
289
|
+
"referrer-policy": "no-referrer",
|
|
290
|
+
"x-robots-tag": "noindex, nofollow",
|
|
291
|
+
"content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${serving.frameAncestors}`,
|
|
292
|
+
// Asked again at each load, so a removal or a revocation holds at once (after the review);
|
|
293
|
+
// the ETag keeps it cheap.
|
|
294
|
+
"cache-control": "private, no-cache",
|
|
295
|
+
"cross-origin-resource-policy": "same-origin",
|
|
296
|
+
"accept-ranges": "bytes",
|
|
297
|
+
});
|
|
298
|
+
if (type === "application/octet-stream") {
|
|
299
|
+
headers.set("content-disposition", "attachment");
|
|
300
|
+
}
|
|
301
|
+
const etag = HEX.test(asset.sha256) ? `"${asset.sha256}"` : null;
|
|
302
|
+
if (etag !== null) {
|
|
303
|
+
headers.set("etag", etag);
|
|
304
|
+
if (notModified(request, etag)) {
|
|
305
|
+
if (!(body instanceof Uint8Array)) {
|
|
306
|
+
await body.cancel();
|
|
307
|
+
}
|
|
308
|
+
return new Response(null, { status: 304, headers });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const size = body instanceof Uint8Array ? body.byteLength : asset.size;
|
|
312
|
+
const range = rangeOf(request.headers.get("range"), size);
|
|
313
|
+
if (range === "unsatisfiable") {
|
|
314
|
+
if (!(body instanceof Uint8Array)) {
|
|
315
|
+
await body.cancel();
|
|
316
|
+
}
|
|
317
|
+
headers.set("content-range", `bytes */${size}`);
|
|
318
|
+
return new Response(null, { status: 416, headers });
|
|
319
|
+
}
|
|
320
|
+
if (range !== null) {
|
|
321
|
+
headers.set("content-range", `bytes ${range.start}-${range.end}/${size}`);
|
|
322
|
+
headers.set("content-length", String(range.end - range.start + 1));
|
|
323
|
+
if (method === "HEAD" && !(body instanceof Uint8Array)) {
|
|
324
|
+
await body.cancel();
|
|
325
|
+
}
|
|
326
|
+
return new Response(method === "HEAD" ? null : asBody(slice(body, range.start, range.end)), {
|
|
327
|
+
status: 206,
|
|
328
|
+
headers,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (body instanceof Uint8Array || method === "HEAD") {
|
|
332
|
+
headers.set("content-length", String(size));
|
|
333
|
+
}
|
|
334
|
+
if (method === "HEAD" && !(body instanceof Uint8Array)) {
|
|
335
|
+
await body.cancel();
|
|
336
|
+
}
|
|
337
|
+
return new Response(method === "HEAD" ? null : asBody(body), { status: 200, headers });
|
|
338
|
+
}
|
package/dist/server/host.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { Displays } from "../displays/displays.ts";
|
|
|
4
4
|
import type { ContentClientMeta } from "../host/client.ts";
|
|
5
5
|
import { type ContentDomainInfo } from "./domain.ts";
|
|
6
6
|
import { type Naming } from "./naming.ts";
|
|
7
|
-
import type { Access, ArtifactStore, AuthorizeAnswer, AuthorizeRequest, Grant, PortholeServer, TicketStore, Upstream } from "./types.ts";
|
|
7
|
+
import type { Access, ArtifactStore, AssetStore, AuthorizeAnswer, AuthorizeRequest, Grant, PortholeServer, TicketStore, Upstream } from "./types.ts";
|
|
8
8
|
/**
|
|
9
9
|
* The host kit (P066): everything around `/server` that every host wrote, so an app writes only
|
|
10
10
|
* its policy (four callbacks) and its settings. Web-standard and runtime-agnostic: Node (through
|
|
@@ -115,6 +115,11 @@ export interface ContentHostOptions<V> {
|
|
|
115
115
|
readonly authorizeTtlSeconds?: number;
|
|
116
116
|
/** Policy 4, source: a stored page by id and version (artifact documents). */
|
|
117
117
|
readonly source?: ArtifactStore["get"];
|
|
118
|
+
/**
|
|
119
|
+
* Policy 5, assets (P089): an artifact's asset library by id, served at `/_blob/<id>` to an
|
|
120
|
+
* access for its artifact; or the store itself, with `bearer` (an explicit opt-in).
|
|
121
|
+
*/
|
|
122
|
+
readonly assets?: AssetStore["get"] | AssetStore;
|
|
118
123
|
readonly upstream?: Upstream;
|
|
119
124
|
/**
|
|
120
125
|
* The health gate, and with it the opaque fallback (P066): the kit checks the content domain
|
|
@@ -152,7 +157,7 @@ export interface EntryOptions<V> {
|
|
|
152
157
|
* authorize route with the viewer. Say what exists the same way for both; `access` says who
|
|
153
158
|
* may see it.
|
|
154
159
|
*/
|
|
155
|
-
readonly at: (scope: string, path: string, viewer: V | null, request: Request) => Awaitable<InstanceRef | null | undefined>;
|
|
160
|
+
readonly at: (scope: string, path: string, viewer: V | null, request: Request) => Awaitable<InstanceRef | FileAddress | null | undefined>;
|
|
156
161
|
/**
|
|
157
162
|
* The app's own sign-in, which comes back to `returnTo` (the authorize URL, as `authorizeUrl`
|
|
158
163
|
* names the app, with the entry's state) once signed in.
|
|
@@ -190,6 +195,43 @@ export interface EntryOptions<V> {
|
|
|
190
195
|
*/
|
|
191
196
|
readonly refusal?: (status: 403 | 404, request: Request, entry: EntryContext) => Awaitable<Response | null | undefined>;
|
|
192
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* What a clean address means when its instance is a version made of files (P081): the instance,
|
|
200
|
+
* the version's own address (`base`, a path ending in `/`: `/v/3/`), and the file the address
|
|
201
|
+
* asks for below it (`""`: the version's entry). The session the entry buys serves every path
|
|
202
|
+
* under `base`, so the page's relative addresses are its own version's. An address that isn't
|
|
203
|
+
* under `base` (`/`, `/style.css`: the latest) goes to `base` + `file`, so a page never mixes
|
|
204
|
+
* versions when a new one is published while it loads. `versionedAddress` reads the usual
|
|
205
|
+
* convention (`/v/<n>/<file>`, else the latest).
|
|
206
|
+
*/
|
|
207
|
+
export interface FileAddress {
|
|
208
|
+
readonly instance: InstanceRef;
|
|
209
|
+
/** A path ending in `/`, each segment of `A-Z a-z 0-9 . _ : ~ -`, no `.` or `..` segment. */
|
|
210
|
+
readonly base: string;
|
|
211
|
+
readonly file?: string;
|
|
212
|
+
/**
|
|
213
|
+
* Whether `base` names this version and no other (`/v/3/`, never `/` or `/latest/`): its files
|
|
214
|
+
* are then immutable there. Default false: revalidated, as an address that may mean another
|
|
215
|
+
* version later.
|
|
216
|
+
*/
|
|
217
|
+
readonly pinned?: boolean;
|
|
218
|
+
}
|
|
219
|
+
/** Whether `entry.at`'s answer is a file set's address rather than an instance. */
|
|
220
|
+
export declare const isFileAddress: (value: InstanceRef | FileAddress) => value is FileAddress;
|
|
221
|
+
/** Kept free on every content origin for an asset library across versions (P081): not built. */
|
|
222
|
+
export declare const ASSET_LIBRARY_PATH = "/_blob/";
|
|
223
|
+
/**
|
|
224
|
+
* The convention for a versioned scope's clean addresses (P081): `/v/<version>/<file>` is that
|
|
225
|
+
* version, pinned; any other path is the latest's `<file>` (`version` null). Null for a
|
|
226
|
+
* `/v/<version>` whose version isn't a name (`A-Z a-z 0-9 . _ : -`), and under `/_blob/`, kept for
|
|
227
|
+
* an asset library outside every version. `versionBase(version)` is the base to answer with.
|
|
228
|
+
*/
|
|
229
|
+
export declare function versionedAddress(path: string): {
|
|
230
|
+
readonly version: string | null;
|
|
231
|
+
readonly file: string;
|
|
232
|
+
} | null;
|
|
233
|
+
/** A version's own address in `versionedAddress`'s convention: `/v/<version>/`. */
|
|
234
|
+
export declare const versionBase: (version: string) => string;
|
|
193
235
|
/** The clean address a redirect entry is opening, as its authorize route decoded it (P070). */
|
|
194
236
|
export interface EntryContext {
|
|
195
237
|
/** The address's label, and the scope it names (null: one the naming never makes). */
|
package/dist/server/host.js
CHANGED
|
@@ -15,6 +15,32 @@ const DEFAULT_HEALTH_LABEL = "porthole-health";
|
|
|
15
15
|
const PROBE_TIMEOUT_MS = 10_000;
|
|
16
16
|
const UNHEALTHY_EVERY_MS = 60_000;
|
|
17
17
|
const HEALTHY_EVERY_MS = 600_000;
|
|
18
|
+
/** Whether `entry.at`'s answer is a file set's address rather than an instance. */
|
|
19
|
+
export const isFileAddress = (value) => "base" in value && "instance" in value;
|
|
20
|
+
/** Kept free on every content origin for an asset library across versions (P081): not built. */
|
|
21
|
+
export const ASSET_LIBRARY_PATH = "/_blob/";
|
|
22
|
+
/**
|
|
23
|
+
* The convention for a versioned scope's clean addresses (P081): `/v/<version>/<file>` is that
|
|
24
|
+
* version, pinned; any other path is the latest's `<file>` (`version` null). Null for a
|
|
25
|
+
* `/v/<version>` whose version isn't a name (`A-Z a-z 0-9 . _ : -`), and under `/_blob/`, kept for
|
|
26
|
+
* an asset library outside every version. `versionBase(version)` is the base to answer with.
|
|
27
|
+
*/
|
|
28
|
+
export function versionedAddress(path) {
|
|
29
|
+
if (path.startsWith(ASSET_LIBRARY_PATH)) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const pinned = /^\/v\/([^/]*)(?:\/(.*))?$/u.exec(path);
|
|
33
|
+
if (pinned === null) {
|
|
34
|
+
return { version: null, file: path.replace(/^\//u, "") };
|
|
35
|
+
}
|
|
36
|
+
const [, version = "", file = ""] = pinned;
|
|
37
|
+
// A version is a name, never a dot segment.
|
|
38
|
+
return /^[A-Za-z0-9._:-]{1,200}$/u.test(version) && !/^\.{1,2}$/u.test(version)
|
|
39
|
+
? { version, file }
|
|
40
|
+
: null;
|
|
41
|
+
}
|
|
42
|
+
/** A version's own address in `versionedAddress`'s convention: `/v/<version>/`. */
|
|
43
|
+
export const versionBase = (version) => `/v/${version}/`;
|
|
18
44
|
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
19
45
|
const json = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
20
46
|
status,
|
|
@@ -141,6 +167,11 @@ export function createContentHost(options) {
|
|
|
141
167
|
hostOrigins: options.appOrigins,
|
|
142
168
|
configs,
|
|
143
169
|
...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
|
|
170
|
+
...(options.assets === undefined
|
|
171
|
+
? {}
|
|
172
|
+
: {
|
|
173
|
+
assets: typeof options.assets === "function" ? { get: options.assets } : options.assets,
|
|
174
|
+
}),
|
|
144
175
|
...(options.tickets === undefined ? {} : { tickets: options.tickets }),
|
|
145
176
|
...(options.upstream === undefined ? {} : { upstream: options.upstream }),
|
|
146
177
|
...(options.entry === undefined
|
|
@@ -631,9 +662,12 @@ export function createContentHost(options) {
|
|
|
631
662
|
return appPage(500, "Something went wrong", "The app couldn't tell who is asking.", "error", method);
|
|
632
663
|
}
|
|
633
664
|
try {
|
|
634
|
-
const
|
|
665
|
+
const answer = scope === null
|
|
635
666
|
? null
|
|
636
667
|
: ((await entry.at(scope, new URL(state.path, "https://x.invalid").pathname, viewer, request)) ?? null);
|
|
668
|
+
// A file set's address (P081) names its instance and where its version lives.
|
|
669
|
+
const address = answer !== null && isFileAddress(answer) ? answer : null;
|
|
670
|
+
const instance = address === null ? answer : address.instance;
|
|
637
671
|
const grant = instance === null ? null : await options.access(instance, viewer, request);
|
|
638
672
|
// The address being opened, decoded, for the app's sign-in and refusal pages.
|
|
639
673
|
const context = {
|
|
@@ -667,7 +701,13 @@ export function createContentHost(options) {
|
|
|
667
701
|
}
|
|
668
702
|
let location;
|
|
669
703
|
try {
|
|
670
|
-
location = await server.enterBy(state, instance, grant
|
|
704
|
+
location = await server.enterBy(state, instance, grant, address === null
|
|
705
|
+
? undefined
|
|
706
|
+
: {
|
|
707
|
+
base: address.base,
|
|
708
|
+
...(address.file === undefined ? {} : { file: address.file }),
|
|
709
|
+
...(address.pinned === true ? { pinned: true } : {}),
|
|
710
|
+
});
|
|
671
711
|
}
|
|
672
712
|
catch {
|
|
673
713
|
return appPage(409, "This can't be opened here", "Open the address again.", "error", method);
|
package/dist/server/index.d.ts
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* content without a valid ticket or cookie gets nothing of the content.
|
|
34
34
|
*/
|
|
35
35
|
export { createServer } from "./server.ts";
|
|
36
|
-
export { createContentHost, HEALTH_PATH, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
|
|
36
|
+
export { createContentHost, HEALTH_PATH, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, ASSET_LIBRARY_PATH, type FileAddress, isFileAddress, versionBase, versionedAddress, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
|
|
37
37
|
export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
|
|
38
38
|
export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
|
|
39
39
|
export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
|
|
@@ -44,4 +44,7 @@ export type { FrameLocation, InstanceRef, ServedDocument } from "../isolation/ty
|
|
|
44
44
|
export { isPortholeCookie, proxyTo, upstreamHeaders, withoutPortholeCookies, type ProxyOptions, } from "./proxy.ts";
|
|
45
45
|
export { statusPageOf as statusPage } from "./pages.ts";
|
|
46
46
|
export { contentHostFor, type ContentHostFor } from "./bootstrap.ts";
|
|
47
|
-
export
|
|
47
|
+
export { checkFileSet, DEFAULT_ENTRY, fileLimits, filePathProblem, type FileLimits, type FileSetProblem, } from "../files/paths.ts";
|
|
48
|
+
export { fileTypeOf, type FileRole, type FileType } from "../files/types.ts";
|
|
49
|
+
export { pseudonymFor } from "./pseudonym.ts";
|
|
50
|
+
export type { Access, ArtifactStore, AssetStore, StoredAsset, FileBody, StoredFile, StoredFiles, StoredVersion, AuthorizeAnswer, AuthorizeRequest, Authorizer, ContentDomain, EntryState, Grant, PortholeServer, ServerOptions, TicketRecord, TicketStore, Upstream, } from "./types.ts";
|
package/dist/server/index.js
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* content without a valid ticket or cookie gets nothing of the content.
|
|
34
34
|
*/
|
|
35
35
|
export { createServer } from "./server.js";
|
|
36
|
-
export { createContentHost, HEALTH_PATH, } from "./host.js";
|
|
36
|
+
export { createContentHost, HEALTH_PATH, ASSET_LIBRARY_PATH, isFileAddress, versionBase, versionedAddress, } from "./host.js";
|
|
37
37
|
export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domain.js";
|
|
38
38
|
export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
|
|
39
39
|
export { FRAME_STATUS_METHOD } from "../isolation/types.js";
|
|
@@ -43,3 +43,7 @@ export { conformancePage } from "../conformance/page.js";
|
|
|
43
43
|
export { isPortholeCookie, proxyTo, upstreamHeaders, withoutPortholeCookies, } from "./proxy.js";
|
|
44
44
|
export { statusPageOf as statusPage } from "./pages.js";
|
|
45
45
|
export { contentHostFor } from "./bootstrap.js";
|
|
46
|
+
// A version made of files (P081): the rules its paths follow, its limits and its types.
|
|
47
|
+
export { checkFileSet, DEFAULT_ENTRY, fileLimits, filePathProblem, } from "../files/paths.js";
|
|
48
|
+
export { fileTypeOf } from "../files/types.js";
|
|
49
|
+
export { pseudonymFor } from "./pseudonym.js";
|