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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 43 additions & 38 deletions public/examples/sandbox-quickstart.mjs
Original file line number Diff line number Diff line change
@@ -1,50 +1,55 @@
import { unwrapOperation } from "@mdbase/connect";
import { createSandbox } from "@mdbase/connect-dev";
import { createSandbox } from "@mdbase-dev/connect-dev";

const { client, transport } = createSandbox({
records: [
{
path: "tasks/first.md",
types: ["task"],
frontmatter: {
type: "task",
title: "Read the collection",
completed: false
}
records: [{
path: "tasks/first.md",
types: ["task"],
frontmatter: {
type: "task",
title: "Read the collection",
completed: false
}
]
}]
});

const first = unwrapOperation(await client.read({ path: "tasks/first.md" }));
// Every operation returns a ConnectOutcome: check ok, then use value or problem.
function required(outcome) {
if (!outcome.ok) throw new Error(`${outcome.problem.code}: ${outcome.problem.message}`);
return outcome.value;
}

const created = unwrapOperation(
await client.create({
const first = required(await client.read({ path: "tasks/first.md" }));

const created = required(await client.create({
type: "task",
path: "tasks/second.md",
frontmatter: {
type: "task",
path: "tasks/second.md",
frontmatter: {
type: "task",
title: "Update one record",
completed: false
}
})
);

const updated = unwrapOperation(
await client.update({
path: created.path,
patch: { completed: true },
if_revision: created.revision
})
);

const tasks = unwrapOperation(
await client.query({
types: ["task"],
limit: 20
})
);
title: "Update one record",
completed: false
}
}));

const updated = required(await client.update({
path: created.path,
patch: { completed: true },
ifRevision: created.revision
}));

// Reusing the old revision is refused instead of overwriting the update.
const stale = await client.update({
path: created.path,
patch: { completed: false },
ifRevision: created.revision
});

const tasks = required(await client.query({
types: ["task"],
limit: 20
}));

console.log(`Read: ${first.frontmatter.title}`);
console.log(`Updated: ${updated.path} (completed: ${updated.frontmatter.completed})`);
console.log(`Stale revision: ${stale.ok ? "accepted" : stale.problem.code}`);
console.log(`Task records: ${tasks.results.length}`);
console.log(`Markdown paths: ${transport.snapshot().map((record) => record.path).join(", ")}`);
216 changes: 119 additions & 97 deletions src/pages/sdk/api/index.astro

Large diffs are not rendered by default.

177 changes: 78 additions & 99 deletions src/pages/sdk/authorization/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,60 @@
import DocsLayout from "../../../components/DocsLayout.astro";
import CodeBlock from "../../../components/CodeBlock.astro";

const stepUp = `const required = ["read", "query", "update"] as const;
const capability = connection.authorizationCapabilities([...required]);
const stepUp = `const granted = await session.ensureCapabilities(["records.create"]);
if (!granted.ok) renderProblem(granted.problem);`;

if (!capability.sufficient) {
await connection.requestOperations([...required], {
returnTo: collectionLocation.authorizationReturnTo()
});
}`;

const listen = `const stop = collectionLocation.onChange(({ connection }) => {
if (!connection) {
renderDisconnected();
return;
const listen = `const stop = session.subscribe(() => {
const snapshot = session.getSnapshot();
switch (snapshot.status) {
case "ready":
renderConnection({ collectionId: snapshot.collectionId, route: snapshot.info.route });
break;
case "authorization_required":
renderReconnect();
break;
case "unavailable":
renderUnavailable(snapshot.reason);
break;
default:
renderStatus(snapshot.status);
}

const info = connection.info();
renderConnection({
collectionId: info.collectionId,
route: info.route,
operations: info.operations
});
});

// Call stop() when the owning UI is destroyed.`;

const recover = `try {
await connection.update(input);
} catch (error) {
if (error instanceof MdbaseConnectError) {
switch (error.recovery) {
case "reauthorize":
await connection.requestOperations(["update"]);
break;
case "refresh":
await refreshVisibleState();
break;
case "resolve_outcome":
await connection.resumePendingMutation(input);
break;
}
}
throw error;
const recover = `const updated = await connection.update(input);
if (updated.ok) return;
switch (updated.problem.recovery) {
case "reauthorize":
await session.authorize("selected");
break;
case "refresh":
await refreshVisibleState();
break;
case "resolve_outcome":
for (const pending of connection.pendingMutations()) await pending.recover();
break;
default:
renderProblem(updated.problem);
}`;

const portableAuthorize = `const controller = new AbortController();

const { connection } = await connect.authorize({
operations: ["describe", "read", "query"],
const authorized = await session.authorize("choose", {
onDeviceCode: ({ userCode, verificationUriComplete }) => {
renderApprovalCode(userCode, verificationUriComplete);
},
signal: controller.signal
});`;
});
if (!authorized.ok) renderProblem(authorized.problem);`;
---

<DocsLayout
title="Authorization"
description="Request operation grants at the point of use and handle narrowing, pause, or revocation."
description="Declare capabilities, request more at the point of use, and handle narrowing, pause, or revocation."
active="authorization"
headings={[
{ href: "#flows", label: "Authorization flows" },
{ href: "#operations", label: "Operation grants" },
{ href: "#capabilities", label: "Capabilities" },
{ href: "#step-up", label: "Step-up authorization" },
{ href: "#connection", label: "Connection state" },
{ href: "#recovery", label: "Recovery" },
Expand All @@ -84,14 +76,14 @@ const { connection } = await connect.authorize({
<h2 id="flows">Use the flow selected by the manifest</h2>
<p>
Web and native-shell manifests use an authorization-code redirect with
PKCE. <code>authorize()</code> navigates away, and the callback route calls
{" "}<code>completeAuthorization()</code>.
PKCE. <code>session.authorize()</code> navigates away, and the callback
route calls <code>session.completeAuthorization()</code>.
</p>
<p>
A <code>distribution: "portable"</code> manifest uses short-code device
authorization with PKCE and a P-256 application key.
<code>authorize()</code> opens the approval page, polls at the server
interval, and resolves with the collection-bound connection after approval.
<code>session.authorize()</code> opens the approval page, polls at the
server interval, and resolves after approval.
</p>
<CodeBlock code={portableAuthorize} language="ts" label="portable-authorization.ts" />
<p>
Expand All @@ -101,79 +93,66 @@ const { connection } = await connect.authorize({
for the complete downloaded-file boundary.
</p>

<h2 id="operations">Choose operations by feature</h2>
<h2 id="capabilities">Declare capabilities by feature</h2>
<p>
The manifest's <code>requirements.capabilities</code> lists what the
application may do. <code>required</code> groups are always requested;
{" "}<code>optional</code> groups are requested when a feature needs them.
An application never requests a capability its manifest does not declare.
</p>
<table class="api-table">
<thead>
<tr>
<th>Feature</th>
<th>Typical operations</th>
<th>Capability</th>
<th>Allows</th>
</tr>
</thead>
<tbody>
<tr>
<td>Browse records</td>
<td><code>describe</code>, <code>read</code>, <code>query</code></td>
</tr>
<tr>
<td>Live refresh</td>
<td><code>changes</code></td>
</tr>
<tr>
<td>Edit records</td>
<td><code>create</code>, <code>update</code></td>
</tr>
<tr>
<td>Move or remove records</td>
<td><code>rename</code>, <code>delete</code></td>
</tr>
<tr>
<td>Use saved views</td>
<td><code>list_views</code>, <code>execute_view</code></td>
</tr>
<tr>
<td>Administer saved view source</td>
<td><code>read_view_source</code>, <code>create_view_source</code>, <code>update_view_source</code>, <code>delete_view_source</code></td>
</tr>
<tr>
<td>Administer collection types</td>
<td><code>read_type</code>, <code>create_type</code>, <code>update_type</code></td>
</tr>
<tr>
<td>Authority timers</td>
<td><code>list_timers</code>, <code>put_timer</code>, <code>cancel_timer</code>, <code>reconcile_timers</code></td>
</tr>
<tr><td><code>collection.read</code></td><td>Describe the collection, read, query and watch records, use saved views, read types, validate</td></tr>
<tr><td><code>records.create</code></td><td>Create records</td></tr>
<tr><td><code>records.edit</code></td><td>Update and rename records</td></tr>
<tr><td><code>records.delete</code></td><td>Delete records</td></tr>
<tr><td><code>views.manage</code></td><td>Create, update and delete saved view sources</td></tr>
<tr><td><code>definitions.manage</code></td><td>Create and update types, assess and apply type packs</td></tr>
<tr><td><code>background.schedule</code></td><td>Authority timers</td></tr>
<tr><td><code>offline.replica</code></td><td>Offline sync</td></tr>
</tbody>
</table>

<h2 id="step-up">Request additional operations at the point of use</h2>
<h2 id="step-up">Request optional capabilities at the point of use</h2>
<p>
Begin with the operations used by the current feature. Inspect the current
gap when a user opens an editing or administration feature.
Begin with the required capabilities. When a user opens a feature that
needs an optional one, ensure it then.
</p>
<CodeBlock code={stepUp} language="ts" label="feature-entry.ts" />
<p>
<code>requestOperations()</code> is a no-op when the current grant is
already sufficient. Otherwise it asks for the least-privilege union of the
existing operations and the new requirements.
<code>ensureCapabilities()</code> returns <code>unchanged</code> when the
current grant already covers the request. Otherwise it asks for the
existing grant plus the new capabilities, and refuses capabilities the
manifest does not declare.
</p>

<h2 id="connection">Render current connection state</h2>
<CodeBlock code={listen} language="ts" label="connection-state.ts" />
<p>
The route is <code>direct</code>, <code>relay</code>, or
{" "}<code>hosted</code>. Display it as status information. The SDK selects
the route. The browser location subscription also reports back and forward
selection changes. A <code>null</code> connection means the bookmarked
collection has no usable authorization.
The session snapshot names its state: <code>unselected</code>,
{" "}<code>authorization_required</code>, <code>checking_setup</code>,
{" "}<code>setup_review_required</code>, <code>ready</code>,
{" "}<code>unavailable</code>, <code>blocked</code>, and the start-up
states. The route is <code>direct</code>, <code>relay</code>, or
{" "}<code>hosted</code>; display it as status information, as the SDK
selects it. Browser back and forward selection changes also notify
subscribers.
</p>

<h2 id="recovery">Use structured recovery actions</h2>
<p>
<code>MdbaseConnectError</code> includes a machine-readable code, current
grant information where relevant, and a recovery action:
<code>retry</code>, <code>reauthorize</code>, <code>refresh</code>,
<code>resolve_outcome</code>, <code>fix_request</code>, or{" "}
<code>none</code>.
A failed outcome's <code>problem</code> has a machine-readable
{" "}<code>code</code>, a <code>category</code>, and a suggested
{" "}<code>recovery</code>, such as <code>retry</code>,
{" "}<code>reauthorize</code>, <code>refresh</code>,
{" "}<code>resolve_outcome</code>, <code>resolve_conflict</code>,
{" "}<code>fix_request</code>, or <code>contact_support</code>.
</p>
<CodeBlock code={recover} language="ts" label="recovery.ts" />
<div class="callout">
Expand All @@ -188,7 +167,7 @@ const { connection } = await connect.authorize({
<h2 id="disconnect">Disconnecting an application</h2>
<p>
<code>connection.forget()</code> clears only that collection's local
authorization state. <code>manager.forgetAll()</code> clears the saved set.
authorization state. <code>mdbase.forgetAll()</code> clears the saved set.
Neither replaces user-controlled revocation at the
collection authority. Provide a clear path to the Connect controller when a
user needs to review, narrow, pause, or revoke a grant.
Expand Down
Loading
Loading