@assistant-ui/appos 0.0.0-stage → 0.0.1

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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunks/ai-call.js +71 -0
  3. package/dist/chunks/ai-sdk.js +66 -0
  4. package/dist/chunks/src.js +1174 -0
  5. package/dist/index.js +1618 -0
  6. package/dist/next-page.js +150 -0
  7. package/dist/next-runtime.js +102 -0
  8. package/dist/next-server.js +50 -0
  9. package/dist/next.js +215 -0
  10. package/dist/pack.js +107 -0
  11. package/dist/server.js +77 -0
  12. package/dist/types/packages/appos-client/src/ai-sdk.d.ts +7 -0
  13. package/dist/types/packages/appos-client/src/index.d.ts +467 -0
  14. package/dist/types/packages/appos-client/src/theme.d.ts +16 -0
  15. package/dist/types/packages/appos-client/src/update-text.d.ts +13 -0
  16. package/dist/types/packages/appos-host/src/AppOSApp.d.ts +20 -0
  17. package/dist/types/packages/appos-host/src/ai-call.d.ts +31 -0
  18. package/dist/types/packages/appos-host/src/ai.d.ts +61 -0
  19. package/dist/types/packages/appos-host/src/embed.d.ts +119 -0
  20. package/dist/types/packages/appos-host/src/index.d.ts +6 -0
  21. package/dist/types/packages/appos-host/src/next/adapter.d.ts +43 -0
  22. package/dist/types/packages/appos-host/src/next/page.d.ts +1 -0
  23. package/dist/types/packages/appos-host/src/next/routes.d.ts +2 -0
  24. package/dist/types/packages/appos-host/src/next/runtime.d.ts +11 -0
  25. package/dist/types/packages/appos-host/src/next/server.d.ts +22 -0
  26. package/dist/types/packages/appos-host/src/pack.d.ts +16 -0
  27. package/dist/types/packages/appos-host/src/server.d.ts +23 -0
  28. package/dist/types/src/lib/ai-spend.d.ts +51 -0
  29. package/dist/types/src/lib/bundle-meta.d.ts +13 -0
  30. package/dist/types/src/lib/color-scheme.d.ts +17 -0
  31. package/dist/types/src/lib/external-link.d.ts +5 -0
  32. package/dist/types/src/lib/frame-pinch.d.ts +6 -0
  33. package/dist/types/src/lib/pack.d.ts +17 -0
  34. package/dist/types/src/lib/swbn/cbor.d.ts +16 -0
  35. package/dist/types/src/lib/swbn/identity.d.ts +121 -0
  36. package/dist/types/src/lib/swbn/integrity.d.ts +51 -0
  37. package/dist/types/src/lib/swbn/keys.d.ts +25 -0
  38. package/dist/types/src/lib/swbn/manifest.d.ts +106 -0
  39. package/dist/types/src/lib/swbn/release.d.ts +39 -0
  40. package/package.json +43 -4
  41. package/README.md +0 -3
@@ -0,0 +1,61 @@
1
+ import { type AiStreamPart } from "./ai-call";
2
+ import { type SpendLimit } from "../../../src/lib/ai-spend";
3
+ export type { AiStreamPart };
4
+ export interface AiRequest {
5
+ /** LanguageModelV4 call options, already filtered (sanitizeAiOptions). */
6
+ options: Record<string, unknown>;
7
+ /** The model the app asked for: a hint the host may ignore. */
8
+ model?: string;
9
+ /** Aborted when the app cancels the call or the frame goes away. */
10
+ signal: AbortSignal;
11
+ }
12
+ /**
13
+ * Serves one AI call: yields stream parts. Throw an AiError (or anything
14
+ * with a string `code` and `message`) to fail it with a code the app sees.
15
+ */
16
+ export type AiService = (request: AiRequest) => AsyncIterable<AiStreamPart> | ReadableStream<AiStreamPart>;
17
+ export interface AiGatewayOptions {
18
+ /** The host's endpoint, e.g. "/api/ai". It receives { model?, options } as JSON and answers with ./server's aiResponse. */
19
+ url: string;
20
+ /** Extra request headers, e.g. a CSRF token. */
21
+ headers?: Record<string, string>;
22
+ /** Defaults to "same-origin". */
23
+ credentials?: RequestCredentials;
24
+ }
25
+ /**
26
+ * An AiService that streams through the host's own backend: POST { model?,
27
+ * options } to `url`, read NDJSON lines ({ part } … then { done } or
28
+ * { error }) back. A non-2xx answer fails the call with its { error } body,
29
+ * so a 429 from the gateway reaches the app as code "rate-limited".
30
+ */
31
+ export declare function aiGateway({ url, headers, credentials }: AiGatewayOptions): AiService;
32
+ /** Where an embed keeps what each app spent today: one visitor's browser, per site. */
33
+ export interface SpendStore {
34
+ get(): string | null;
35
+ set(value: string): void;
36
+ }
37
+ /** localStorage, or memory for this page load when the browser refuses it. */
38
+ export declare function browserSpendStore(): SpendStore;
39
+ /**
40
+ * One app's daily AI spend limit in an embed, metered like appOS's signed-out
41
+ * shell (src/lib/ai-budget.ts): each call's token usage times the model's list
42
+ * price (src/lib/ai-spend.ts), per UTC day. A call starts only while the app
43
+ * is under its limit.
44
+ */
45
+ export interface AiBudget {
46
+ /** Throws AiError("over-limit") once the app spent its limit today. */
47
+ check(): void;
48
+ /** Meters one stream part (a finish part's usage); `model` prices it. */
49
+ meter(part: AiStreamPart, model: string | undefined): void;
50
+ }
51
+ /** What an embedded app sees over its limit. */
52
+ export declare const embedOverLimitMessage: (limit: SpendLimit) => string;
53
+ export declare function aiBudget(app: string, limit: () => SpendLimit, store: SpendStore): AiBudget;
54
+ /**
55
+ * Serves one call on the app's port, as appOS's shell does
56
+ * (src/lib/capabilities/ai.ts): { op: "stream", options, model? } in;
57
+ * { part } messages, then { done } or { error }, out. { op: "abort" } stops
58
+ * it. `allowed` runs the permission check (and prompt) first, then `budget`
59
+ * the app's spend limit. Returns a cleanup that aborts the call.
60
+ */
61
+ export declare function serveAiPort(port: MessagePort, service: AiService | undefined, allowed: () => Promise<boolean>, budget?: AiBudget): () => void;
@@ -0,0 +1,119 @@
1
+ import { type FramePermission } from "../../../src/lib/swbn/manifest";
2
+ import { type ColorSchemePreference } from "../../../src/lib/color-scheme";
3
+ import { type AiService, type SpendStore } from "./ai";
4
+ import { type SpendLimit } from "../../../src/lib/ai-spend";
5
+ /** The hosted sandbox: one origin per app identity. */
6
+ export declare const DEFAULT_SANDBOX = "https://{key}.apps.auiusercontent.com";
7
+ /** The capabilities a host can serve. */
8
+ export type Capability = "ai";
9
+ export type PermissionState = "granted" | "denied" | "prompt";
10
+ /** Default answers. Missing means "prompt". */
11
+ export type Permissions = Partial<Record<Capability, PermissionState>>;
12
+ /** What the host provides. A capability with no service is unavailable to the app. */
13
+ export interface Services {
14
+ ai?: AiService;
15
+ }
16
+ /** The app as the host knows it once the bundle's signatures check out. */
17
+ export interface EmbeddedApp {
18
+ /** The app's identity: the signed bundle's DID, or an unsigned bundle's URL. */
19
+ id: string;
20
+ /** Signed (.swbn): its keys decide what runs. Unsigned (.wbn): its URL does. */
21
+ signed: boolean;
22
+ name: string;
23
+ /** data: URL, if the bundle has an icon. */
24
+ icon?: string;
25
+ /** The sandbox origin it runs on. */
26
+ origin: string;
27
+ }
28
+ export interface PermissionRequest {
29
+ capability: Capability;
30
+ app: EmbeddedApp;
31
+ }
32
+ export declare class EmbedError extends Error {
33
+ readonly code: string;
34
+ constructor(code: string, message: string);
35
+ }
36
+ export interface EmbedOptions {
37
+ /**
38
+ * The bundle: a signed .swbn (a URL or its bytes), or an unsigned .wbn at
39
+ * a URL on this page's own origin, https or http on localhost.
40
+ */
41
+ src: string | URL | ArrayBuffer | Uint8Array;
42
+ services?: Services;
43
+ permissions?: Permissions;
44
+ /**
45
+ * The app's daily AI spend limit in US dollars, per UTC day, as in appOS:
46
+ * $5 (DEFAULT_LIMIT) when missing, null for none, at most $10,000. Metered in this page per
47
+ * visitor (localStorage, per app), from each call's token usage and the
48
+ * model's list price. It stops a runaway app; it doesn't protect your
49
+ * gateway from callers that skip the page.
50
+ */
51
+ spendLimit?: SpendLimit;
52
+ /** Where spend is kept. Default: localStorage. */
53
+ spendStore?: SpendStore;
54
+ /**
55
+ * Light or dark for the app. "system" (the default) follows this page's
56
+ * prefers-color-scheme. Pass your site's own theme to have the app follow
57
+ * your toggle. Sets the iframe's CSS color-scheme and tells the app, whose
58
+ * page gets the "dark" class on <html> before it paints.
59
+ */
60
+ colorScheme?: ColorSchemePreference;
61
+ /**
62
+ * The sandbox origin template, with `{key}` for the app's label. Default
63
+ * DEFAULT_SANDBOX. The host's origin must be one of the sandbox's allowed
64
+ * parents (sandbox/src/config.ts).
65
+ */
66
+ sandbox?: string;
67
+ /** Answers a "prompt" permission. Without it, "prompt" is a no. */
68
+ onPermissionRequest?: (request: PermissionRequest) => boolean | Promise<boolean>;
69
+ /** The bundle verified; the frame is booting it. */
70
+ onVerified?: (app: EmbeddedApp) => void;
71
+ /** The app's own document has loaded. */
72
+ onLoad?: (app: EmbeddedApp) => void;
73
+ onError?: (error: EmbedError) => void;
74
+ /** The app's console output and errors. */
75
+ onLog?: (entry: {
76
+ level: string;
77
+ text: string;
78
+ time: number;
79
+ }) => void;
80
+ }
81
+ /** What embedApp's handle can change without reloading the app. */
82
+ export type LiveOptions = Omit<EmbedOptions, "src" | "sandbox" | "spendStore">;
83
+ export interface Embed {
84
+ /** Swaps services, permissions or callbacks; the app keeps running. */
85
+ update(options: LiveOptions): void;
86
+ /** Stops listening, aborts open calls and blanks the frame. */
87
+ destroy(): void;
88
+ }
89
+ /** The iframe's sandbox flags: the same as appOS's app frames. */
90
+ export declare const SANDBOX_FLAGS = "allow-scripts allow-same-origin allow-forms allow-popups allow-downloads";
91
+ /** The app's origin for a sandbox template. */
92
+ export declare function sandboxOrigin(template: string, key: string): string;
93
+ export interface LoadedBundle {
94
+ bytes: ArrayBuffer;
95
+ /** SHA-256 of the bytes, hex: what the sandbox stores it under. */
96
+ hash: string;
97
+ /** The DID (signed) or the URL (unsigned). */
98
+ id: string;
99
+ signed: boolean;
100
+ /** The origin label: hash of the DID or URL. */
101
+ key: string;
102
+ name: string;
103
+ icon?: string;
104
+ /** The manifest's appos.permissions: what the frame is delegated. */
105
+ permissions?: FramePermission[];
106
+ }
107
+ /**
108
+ * Fetches a bundle and checks it as far as the host can. Signed: a valid
109
+ * integrity block, every signature valid, a DID the sandbox runs; the
110
+ * sandbox checks it again, fully (keys for did:web/did:plc, the label,
111
+ * downgrades), before it runs. Unsigned: a .wbn from this page's own
112
+ * origin, whose URL becomes its identity; the sandbox checks that too.
113
+ */
114
+ export declare function loadBundle(src: EmbedOptions["src"], signal?: AbortSignal): Promise<LoadedBundle>;
115
+ /**
116
+ * Runs the app at `src` in `iframe`. Returns at once; progress and errors
117
+ * come through the callbacks.
118
+ */
119
+ export declare function embedApp(iframe: HTMLIFrameElement, options: EmbedOptions): Embed;
@@ -0,0 +1,6 @@
1
+ export { AppOSApp, type AppOSAppProps } from "./AppOSApp";
2
+ export { DEFAULT_SANDBOX, EmbedError, embedApp, loadBundle, type Capability, type Embed, type EmbedOptions, type EmbeddedApp, type LiveOptions, type PermissionRequest, type PermissionState, type Permissions, type Services, } from "./embed";
3
+ export { aiGateway, type AiGatewayOptions, type AiRequest, type AiService, type AiStreamPart, type SpendStore } from "./ai";
4
+ export type { SpendLimit } from "../../../src/lib/ai-spend";
5
+ export { AiError, type AiErrorCode, type AiErrorData } from "./ai-call";
6
+ export type { ColorScheme, ColorSchemePreference } from "../../../src/lib/color-scheme";
@@ -0,0 +1,43 @@
1
+ interface Output {
2
+ id: string;
3
+ pathname: string;
4
+ filePath?: string;
5
+ sourcePage?: string;
6
+ parentOutputId?: string;
7
+ fallback?: {
8
+ filePath?: string;
9
+ };
10
+ }
11
+ interface BuildContext {
12
+ outputs: {
13
+ pages: Output[];
14
+ pagesApi: Output[];
15
+ appPages: Output[];
16
+ appRoutes: Output[];
17
+ prerenders: Output[];
18
+ staticFiles: Output[];
19
+ middleware?: Output;
20
+ };
21
+ projectDir: string;
22
+ distDir: string;
23
+ config: {
24
+ pageExtensions?: string[];
25
+ };
26
+ }
27
+ /** Names in the project's .env files that aren't NEXT_PUBLIC_: server secrets. */
28
+ export declare function serverEnvNames(projectDir: string): string[];
29
+ export declare function writeApp(ctx: BuildContext): Promise<{
30
+ out: string;
31
+ routes: string[];
32
+ warnings: string[];
33
+ }>;
34
+ declare const adapter: {
35
+ name: string;
36
+ modifyConfig<C extends {
37
+ images?: object;
38
+ }>(config: C, { phase }: {
39
+ phase: string;
40
+ }): C;
41
+ onBuildComplete(ctx: BuildContext): Promise<void>;
42
+ };
43
+ export default adapter;
@@ -0,0 +1 @@
1
+ export declare function install(): void;
@@ -0,0 +1,2 @@
1
+ export type Params = Record<string, string | string[]>;
2
+ export declare function compile(pathname: string): (path: string) => Params | undefined;
@@ -0,0 +1,11 @@
1
+ type RouteModule = Record<string, unknown>;
2
+ /** The AI_GATEWAY_API_KEY that sends the gateway provider to appOS (cloud/ai.ts). */
3
+ export declare const APPOS_GATEWAY_KEY = "appos";
4
+ export declare function serve(table: {
5
+ pathname: string;
6
+ mod: RouteModule;
7
+ }[], env?: Record<string, string>): {
8
+ /** `secrets`: the cloud's env for this app (its server secrets); none in the page. */
9
+ fetch(request: Request, secrets?: Record<string, unknown>): Promise<Response>;
10
+ };
11
+ export {};
@@ -0,0 +1,22 @@
1
+ export declare class NextRequest extends Request {
2
+ get nextUrl(): URL;
3
+ get cookies(): {
4
+ get: (name: string) => {
5
+ name: string;
6
+ value: string;
7
+ } | undefined;
8
+ getAll: () => {
9
+ name: string;
10
+ value: string;
11
+ }[];
12
+ has: (name: string) => boolean;
13
+ };
14
+ }
15
+ export declare class NextResponse extends Response {
16
+ static json(body: unknown, init?: ResponseInit): NextResponse;
17
+ static redirect(url: string | URL, init?: number | ResponseInit): NextResponse;
18
+ static next(): never;
19
+ static rewrite(): never;
20
+ }
21
+ /** Runs `task` after the response, as Next's `after()` does. */
22
+ export declare function after(task: Promise<unknown> | (() => unknown)): void;
@@ -0,0 +1,16 @@
1
+ export interface PackOptions {
2
+ /** The built app: index.html at its root, plus its assets and manifest. */
3
+ dir: string;
4
+ /** Where to write the .wbn. "[hash]" in the name becomes the first 12 hex digits of its SHA-256. */
5
+ out: string;
6
+ }
7
+ export interface PackResult {
8
+ /** The file written. */
9
+ out: string;
10
+ /** SHA-256 of the .wbn, hex. */
11
+ hash: string;
12
+ size: number;
13
+ files: number;
14
+ }
15
+ /** Packs `dir` into a .wbn at `out`. `/index.html` is also served at `/`, the primary URL. */
16
+ export declare function pack({ dir, out }: PackOptions): Promise<PackResult>;
@@ -0,0 +1,23 @@
1
+ import { AiError, type AiErrorData } from "./ai-call";
2
+ export { AiError, type AiErrorData };
3
+ /** An AI SDK LanguageModelV4 (e.g. anthropic("claude-haiku-5-5")), loosely typed. */
4
+ export interface StreamingModel {
5
+ doStream(options: never): PromiseLike<{
6
+ stream: ReadableStream<unknown>;
7
+ }>;
8
+ }
9
+ export interface AiResponseOptions {
10
+ /** The model for this call; `hint` is the id the app asked for. */
11
+ model: (hint: string | undefined) => StreamingModel | Promise<StreamingModel>;
12
+ /** The request's signal: a closed connection stops the model call. */
13
+ signal?: AbortSignal;
14
+ /** Extra headers for the streaming response, e.g. rate-limit counters. */
15
+ headers?: HeadersInit;
16
+ }
17
+ /** A failed call as the embed reads it: { error: { code, message } }. */
18
+ export declare function aiErrorResponse(status: number, code: AiErrorData["code"], message: string, headers?: HeadersInit): Response;
19
+ /**
20
+ * Runs one AI call and streams it: NDJSON lines { part } …, then { done }
21
+ * or { error }. A body that isn't a valid call answers 400 (or 413).
22
+ */
23
+ export declare function aiResponse(body: unknown, { model, signal, headers }: AiResponseOptions): Promise<Response>;
@@ -0,0 +1,51 @@
1
+ /** US dollars per million tokens. */
2
+ export interface ModelPrice {
3
+ input: number;
4
+ output: number;
5
+ cacheRead: number;
6
+ cacheWrite: number;
7
+ }
8
+ /**
9
+ * Anthropic's list prices (platform.claude.com pricing, November 2026). A
10
+ * model id matches the longest key it starts with, so dated or suffixed ids
11
+ * price as their family. Haiku 5.5 prompts over 100K tokens cost 5x; calls
12
+ * here are capped well below that in practice, so it is not modeled.
13
+ */
14
+ export declare const AI_PRICES: Record<string, ModelPrice>;
15
+ /** A model the table doesn't know costs as much as the dearest one, so a limit never under-counts. */
16
+ export declare const UNKNOWN_MODEL_PRICE: ModelPrice;
17
+ export declare function priceOf(model: string): ModelPrice;
18
+ /** The AI SDK's LanguageModelV4 usage (a finish part's, or a generate result's), loosely. */
19
+ export interface AiUsage {
20
+ inputTokens?: {
21
+ total?: number;
22
+ noCache?: number;
23
+ cacheRead?: number;
24
+ cacheWrite?: number;
25
+ } | number;
26
+ outputTokens?: {
27
+ total?: number;
28
+ } | number;
29
+ }
30
+ /** A call's cost in micro-dollars (millionths of a dollar), rounded up. */
31
+ export declare function costMicros(model: string, usage: AiUsage | undefined): number;
32
+ /** Dollars per day; null is no limit. */
33
+ export type SpendLimit = number | null;
34
+ export declare const LIMIT_PRESETS: readonly [1, 5, 20];
35
+ /** What the permission prompt picks, and what an app with no limit set gets. */
36
+ export declare const DEFAULT_LIMIT: SpendLimit;
37
+ /** A custom limit is a whole number of cents, up to this. */
38
+ export declare const MAX_LIMIT = 10000;
39
+ /** A limit as sent or stored, or undefined if it isn't one. */
40
+ export declare function parseLimit(v: unknown): SpendLimit | undefined;
41
+ export declare const limitMicros: (limit: SpendLimit) => number;
42
+ /** "$5", "$2.50", "$0.004". */
43
+ export declare function formatUsd(dollars: number): string;
44
+ export declare const formatMicros: (micros: number) => string;
45
+ export declare function formatLimit(limit: SpendLimit): string;
46
+ /** Limits are per UTC day, on every path. */
47
+ export declare const utcDay: (now?: number) => string;
48
+ /** What an app sees when it is over its limit. */
49
+ export declare function overLimitMessage(limit: SpendLimit): string;
50
+ /** What an app sees when the user has no AI key. */
51
+ export declare const NO_KEY_MESSAGE = "Add your AI key in appOS Settings.";
@@ -0,0 +1,13 @@
1
+ export interface BundleMeta {
2
+ /** Manifest name, else the primary document's <title>. */
3
+ name?: string;
4
+ /** The app icon as a data: URL. */
5
+ icon?: string;
6
+ }
7
+ /**
8
+ * Reads the app's name and icon from a Web Bundle. The icon comes from, in
9
+ * order: the web app manifest, `<link rel="apple-touch-icon">` or
10
+ * `<link rel="icon">` in the primary document, then `/favicon.*`.
11
+ * Throws if the bytes are not a Web Bundle.
12
+ */
13
+ export declare function readBundleMeta(bytes: Uint8Array): BundleMeta;
@@ -0,0 +1,17 @@
1
+ export type ColorScheme = "light" | "dark";
2
+ /** What a shell asks for: a scheme, or "system" to follow its own page. */
3
+ export type ColorSchemePreference = ColorScheme | "system";
4
+ export declare const COLOR_SCHEME_MESSAGE = "appos:color-scheme";
5
+ export declare function isColorScheme(value: unknown): value is ColorScheme;
6
+ export declare function colorSchemeMessage(scheme: ColorScheme): {
7
+ type: string;
8
+ scheme: ColorScheme;
9
+ };
10
+ /** "system" as this page sees it now: its own prefers-color-scheme. */
11
+ export declare function resolveColorScheme(preference: ColorSchemePreference | undefined): ColorScheme;
12
+ /**
13
+ * Calls `onScheme` with the resolved scheme now and whenever it changes:
14
+ * for "system", when this page's prefers-color-scheme does. Returns a stop
15
+ * function.
16
+ */
17
+ export declare function watchColorScheme(preference: ColorSchemePreference | undefined, onScheme: (scheme: ColorScheme) => void): () => void;
@@ -0,0 +1,5 @@
1
+ export declare const OPEN_EXTERNAL = "appos:open-external";
2
+ /** The URL to open: https, or http on a loopback host. Anything else (javascript:, data:, blob:, file:) is refused. */
3
+ export declare function externalUrl(value: unknown): string | undefined;
4
+ /** Opens `url` as a fresh top-level page: no opener, no referrer. Returns false when the URL was refused. */
5
+ export declare function openExternal(value: unknown, open?: typeof window.open): boolean;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Hands ctrl+wheel on `iframe` to the app at `origin`, at the same point in
3
+ * the frame's own pixels. `skip` leaves the pinch to the page (the canvas
4
+ * layout zooms the canvas). Returns the cleanup.
5
+ */
6
+ export declare function forwardFramePinch(iframe: HTMLIFrameElement, origin: string, skip?: () => boolean): () => void;
@@ -0,0 +1,17 @@
1
+ export declare const MIME: Record<string, string>;
2
+ export declare function mimeFor(path: string): string;
3
+ export interface PackFile {
4
+ /** URL path inside the bundle, e.g. "/index.html". */
5
+ path: string;
6
+ body: Uint8Array | string;
7
+ }
8
+ /**
9
+ * Normalizes a file path to "/a/b.js". Rejects empty paths, `..`, and
10
+ * paths reserved by the sandbox.
11
+ */
12
+ export declare function normalizePath(input: string): string;
13
+ /**
14
+ * Builds a .wbn. `/index.html` is also served at `/`, the primary URL, and
15
+ * `/a/index.html` at `/a`.
16
+ */
17
+ export declare function packFiles(files: PackFile[]): Uint8Array;
@@ -0,0 +1,16 @@
1
+ export type CborValue = number | bigint | boolean | null | string | Uint8Array | CborValue[] | Map<CborValue, CborValue>;
2
+ export interface CborItem {
3
+ value: CborValue;
4
+ start: number;
5
+ end: number;
6
+ /** For arrays and maps: the items inside, with their byte ranges. */
7
+ items?: CborItem[];
8
+ }
9
+ export declare class CborError extends Error {
10
+ }
11
+ /** Reads one CBOR item at `offset`. Trailing bytes are left alone. */
12
+ export declare function readCbor(bytes: Uint8Array, offset?: number): CborItem;
13
+ /** Decodes a whole buffer that must hold exactly one CBOR item. */
14
+ export declare function decodeCbor(bytes: Uint8Array): CborValue;
15
+ /** Encodes a value as deterministic CBOR. */
16
+ export declare function encodeCbor(value: CborValue): Uint8Array;
@@ -0,0 +1,121 @@
1
+ import { type PublicKey } from "./keys";
2
+ export type DidMethod = "key" | "web" | "plc";
3
+ export type AppIdentity = {
4
+ method: "key";
5
+ id: string;
6
+ key: PublicKey;
7
+ } | {
8
+ method: "web";
9
+ id: string;
10
+ host: string;
11
+ path: string[];
12
+ url: string;
13
+ } | {
14
+ method: "plc";
15
+ id: string;
16
+ url: string;
17
+ };
18
+ /** True for a public hostname: 2+ lowercase DNS labels, not an IP. */
19
+ export declare function isPublicHostname(host: string): boolean;
20
+ /** True for a public hostname that names no private or special-use network. */
21
+ export declare function isPublicHost(host: string): boolean;
22
+ /** The did:key for an Ed25519 public key. */
23
+ export declare function didKeyFor(raw: Uint8Array): string;
24
+ /** Parses a DID this sandbox can run, or returns undefined. */
25
+ export declare function parseDid(id: unknown): AppIdentity | undefined;
26
+ /** Characters of base32 in a label: all 256 bits of SHA-256. */
27
+ export declare const LABEL_CHARS = 52;
28
+ /** The origin label a DID runs on. */
29
+ export declare function labelForId(id: string): Promise<string>;
30
+ /**
31
+ * The origin label of an app served from a URL (decision 17): the same
32
+ * hash as a DID's, of its normalized URL (src/lib/remote.ts). A URL starts
33
+ * with "https:" or "http:", a DID with "did:", so the two never collide.
34
+ */
35
+ export declare function labelForUrl(base: string): Promise<string>;
36
+ /**
37
+ * The identity of an unsigned .wbn served at `raw` (appos-host embeds): its
38
+ * URL without query or fragment. Only https, or http on localhost for dev;
39
+ * its origin label is labelForUrl of it. Undefined if not allowed.
40
+ */
41
+ export declare function bundleUrlId(raw: unknown): string | undefined;
42
+ /**
43
+ * appOS's own hosts: app origins, the dashboard and its account's
44
+ * workers.dev names. Nothing fetches these on an app's behalf.
45
+ */
46
+ export declare function isPlatformHost(host: string): boolean;
47
+ /** True if a label can belong to an app identity (no hyphen, 52 base32). */
48
+ export declare function isAppLabel(label: string): boolean;
49
+ /**
50
+ * The keys a DID document lets sign bundles: Ed25519 and P-256 keys in
51
+ * assertionMethod, each embedded or a "<did>#fragment" reference into this
52
+ * document's verificationMethod, with controller === the DID. Keys
53
+ * elsewhere (authentication, other documents) don't count. Other key types,
54
+ * such as the secp256k1 atproto key of most did:plc accounts, are skipped.
55
+ */
56
+ export declare function keysFromDidDocument(doc: unknown, did: string): string[];
57
+ /**
58
+ * The update feeds (updates.json URLs) a DID document names in a service
59
+ * entry `{ "type": "AppOSUpdates", "serviceEndpoint": "https://…" }`. Only
60
+ * string https endpoints count; at most four.
61
+ */
62
+ export declare function updateFeedsFromDidDocument(doc: unknown, did: string): string[];
63
+ /** The atproto handle a did:plc document claims (not verified). */
64
+ export declare function claimedHandle(doc: unknown): string | undefined;
65
+ export interface PublisherKeys {
66
+ keys: string[];
67
+ /** Where the keys came from, e.g. the did.json URL. */
68
+ sources: string[];
69
+ /** False when the publisher could not be asked (offline, down). */
70
+ reached: boolean;
71
+ }
72
+ /** Answers "which keys may sign for this DID right now?" for one method. */
73
+ export interface KeyResolver {
74
+ resolveAllowedKeys(identity: AppIdentity, fetcher?: (url: string) => Promise<Response>): Promise<PublisherKeys>;
75
+ }
76
+ /**
77
+ * Resolves did:web and did:plc documents through the sandbox's same-origin
78
+ * proxy, GET /__appos/did?id=<did> (see sandbox/api.ts).
79
+ */
80
+ export declare const didDocumentResolver: KeyResolver;
81
+ /** did:key needs no network: the DID is the key. */
82
+ export declare const didKeyResolver: KeyResolver;
83
+ export declare const RESOLVERS: Record<DidMethod, KeyResolver>;
84
+ /** What an origin remembers about the app it holds. */
85
+ export interface VerifiedIdentity {
86
+ id: string;
87
+ method: DidMethod;
88
+ /** Keys that signed the stored bundle. */
89
+ signers: string[];
90
+ /** Keys the DID allows now. */
91
+ keys: string[];
92
+ /** The key list seen at first install. */
93
+ pinnedKeys: string[];
94
+ /** The current key list differs from the pinned one. */
95
+ keysChanged: boolean;
96
+ sources: string[];
97
+ verifiedAt: number;
98
+ /** Verified from the cached key list because the publisher was unreachable. */
99
+ offline?: boolean;
100
+ /** did:plc: the handle the document claims, unverified. */
101
+ handle?: string;
102
+ }
103
+ export declare class IdentityError extends Error {
104
+ code: string;
105
+ }
106
+ /** The signer is listed by the DID but not trusted from before: needs a takeover. */
107
+ export declare class KeysChangedError extends IdentityError {
108
+ code: string;
109
+ }
110
+ /**
111
+ * Decides whether `signers` may run as the DID `id` on the origin `label`.
112
+ * `previous` is what the origin stored last time, for pinning and offline use.
113
+ */
114
+ export declare function checkIdentity(id: string, signers: string[], label: string | undefined, { previous, fetcher, resolvers, takeover, now, }?: {
115
+ previous?: VerifiedIdentity;
116
+ /** The user chose to replace the app (its data is erased): accept new keys. */
117
+ takeover?: boolean;
118
+ fetcher?: (url: string) => Promise<Response>;
119
+ resolvers?: Partial<Record<DidMethod, KeyResolver>>;
120
+ now?: number;
121
+ }): Promise<VerifiedIdentity>;
@@ -0,0 +1,51 @@
1
+ import { type PublicKey } from "./keys";
2
+ export declare const MAGIC: Uint8Array<ArrayBuffer>;
3
+ /**
4
+ * "2b\0\0", what Chrome and wbn-sign 0.3.x write and read. (The explainer's
5
+ * text says "2\0\0\0"; implementations use 2b.) The only version accepted.
6
+ */
7
+ export declare const VERSION: Uint8Array<ArrayBuffer>;
8
+ export interface BundleSignature {
9
+ key: PublicKey;
10
+ signature: Uint8Array;
11
+ /** The signature's attributes map, as raw CBOR. */
12
+ attributes: Uint8Array;
13
+ }
14
+ export interface SignedBundle {
15
+ webBundleId: string;
16
+ signatures: BundleSignature[];
17
+ /** The integrity block with an empty signature list: part of what's signed. */
18
+ stripped: Uint8Array;
19
+ /** The .wbn after the integrity block. */
20
+ bundle: Uint8Array;
21
+ }
22
+ /** True if the bytes start with the integrity block magic. */
23
+ export declare function isSigned(bytes: Uint8Array): boolean;
24
+ /** True if the bytes look like an unsigned Web Bundle. */
25
+ export declare function isWebBundle(bytes: Uint8Array): boolean;
26
+ /** Parses the integrity block. Does not check any signature. */
27
+ export declare function parseSignedBundle(bytes: Uint8Array): SignedBundle;
28
+ /** The .wbn inside a signed bundle, or the bytes as they are if unsigned. */
29
+ export declare function innerBundle(bytes: Uint8Array): Uint8Array;
30
+ /** The bytes a signature covers. */
31
+ export declare function dataToBeSigned(bundleHash: Uint8Array, stripped: Uint8Array, attributes: Uint8Array): Uint8Array;
32
+ export declare function sha512(bytes: Uint8Array): Promise<Uint8Array>;
33
+ /** Decompresses a 33-byte P-256 point to the 65-byte uncompressed form. */
34
+ export declare function decompressP256(raw: Uint8Array): Uint8Array;
35
+ /** DER ECDSA-Sig-Value to raw r||s (64 bytes). Raw input passes through. */
36
+ export declare function derToRaw(sig: Uint8Array): Uint8Array;
37
+ /**
38
+ * Checks every signature against the bundle. Throws unless all of them are
39
+ * valid. Returns the signing keys as "ed25519:<base64url>" strings. Says
40
+ * nothing about whether the keys may sign for the bundle's id.
41
+ */
42
+ export declare function verifySignatures(signed: SignedBundle): Promise<string[]>;
43
+ /** Something that can sign: a WebCrypto key pair, or a Node key in the CLI. */
44
+ export interface Signer {
45
+ key: PublicKey;
46
+ sign(data: Uint8Array): Promise<Uint8Array>;
47
+ }
48
+ /** Wraps an Ed25519 WebCrypto private key (extractable or not). */
49
+ export declare function webCryptoSigner(privateKey: CryptoKey, publicRaw: Uint8Array): Signer;
50
+ /** Signs a .wbn (or re-signs a .swbn's inner bundle) into a .swbn. */
51
+ export declare function signBundle(bytes: Uint8Array, webBundleId: string, signers: Signer[]): Promise<Uint8Array>;
@@ -0,0 +1,25 @@
1
+ export type KeyType = "ed25519" | "ecdsa-p256";
2
+ export interface PublicKey {
3
+ type: KeyType;
4
+ raw: Uint8Array;
5
+ }
6
+ /** RFC 4648 base32, lowercase, no padding. */
7
+ export declare function base32(bytes: Uint8Array): string;
8
+ export declare function toBase64Url(bytes: Uint8Array): string;
9
+ /** Decodes base64 or base64url, padded or not. Throws on anything else. */
10
+ export declare function fromBase64(text: string): Uint8Array;
11
+ export declare function formatKey(key: PublicKey): string;
12
+ /** Parses "ed25519:<base64>" (or "ecdsa-p256:…"). Returns undefined if invalid. */
13
+ export declare function parseKey(text: unknown): PublicKey | undefined;
14
+ /** The canonical text form of a key string, or undefined if invalid. */
15
+ export declare function normalizeKey(text: unknown): string | undefined;
16
+ export declare function sha256(bytes: Uint8Array): Promise<Uint8Array>;
17
+ /** Decodes lowercase unpadded base32. Undefined unless it round-trips. */
18
+ export declare function fromBase32(text: string): Uint8Array | undefined;
19
+ export declare function base58btc(bytes: Uint8Array): string;
20
+ export declare function fromBase58btc(text: string): Uint8Array | undefined;
21
+ /** "z6Mk…" (Ed25519) or "zDn…" (P-256, compressed) multibase to a key. */
22
+ export declare function parseMultikey(text: unknown): PublicKey | undefined;
23
+ export declare function toMultikey(key: PublicKey): string;
24
+ /** A JWK (OKP/Ed25519 or EC/P-256) to a key. */
25
+ export declare function parseJwk(jwk: unknown): PublicKey | undefined;