inboxer 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +376 -2
- package/dist/app.d.ts +6 -0
- package/dist/app.js +56 -0
- package/dist/auth.d.ts +33 -0
- package/dist/auth.js +111 -0
- package/dist/config.d.ts +23 -0
- package/dist/config.js +90 -0
- package/dist/core/address.d.ts +6 -0
- package/dist/core/address.js +16 -0
- package/dist/core/attachments.d.ts +9 -0
- package/dist/core/attachments.js +30 -0
- package/dist/core/context.d.ts +10 -0
- package/dist/core/context.js +21 -0
- package/dist/core/mail.d.ts +170 -0
- package/dist/core/mail.js +656 -0
- package/dist/core/sync.d.ts +16 -0
- package/dist/core/sync.js +44 -0
- package/dist/core/text.d.ts +8 -0
- package/dist/core/text.js +45 -0
- package/dist/core/threads.d.ts +21 -0
- package/dist/core/threads.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +51 -0
- package/dist/mcp.d.ts +5 -0
- package/dist/mcp.js +198 -0
- package/dist/provider/index.d.ts +3 -0
- package/dist/provider/index.js +11 -0
- package/dist/provider/resend.d.ts +8 -0
- package/dist/provider/resend.js +184 -0
- package/dist/provider/types.d.ts +77 -0
- package/dist/provider/types.js +6 -0
- package/dist/store.d.ts +54 -0
- package/dist/store.js +148 -0
- package/dist/types.d.ts +138 -0
- package/dist/types.js +1 -0
- package/dist/ui/assets.d.ts +8 -0
- package/dist/ui/assets.js +13 -0
- package/dist/ui/routes.d.ts +11 -0
- package/dist/ui/routes.js +232 -0
- package/dist/ui/static/app.js +27 -0
- package/dist/ui/static/htmx.min.js +1 -0
- package/dist/ui/static/style.css +179 -0
- package/dist/ui/strings.d.ts +67 -0
- package/dist/ui/strings.js +67 -0
- package/dist/ui/views.d.ts +45 -0
- package/dist/ui/views.js +275 -0
- package/package.json +81 -4
- package/skills/inboxer/SKILL.md +118 -0
- package/src/app.ts +56 -0
- package/src/auth.ts +119 -0
- package/src/config.ts +92 -0
- package/src/core/address.ts +19 -0
- package/src/core/attachments.ts +33 -0
- package/src/core/context.ts +28 -0
- package/src/core/mail.ts +737 -0
- package/src/core/sync.ts +51 -0
- package/src/core/text.ts +52 -0
- package/src/core/threads.ts +102 -0
- package/src/index.ts +93 -0
- package/src/mcp.ts +233 -0
- package/src/provider/index.ts +14 -0
- package/src/provider/resend.ts +235 -0
- package/src/provider/types.ts +82 -0
- package/src/store.ts +187 -0
- package/src/types.ts +140 -0
- package/src/ui/assets.ts +21 -0
- package/src/ui/routes.ts +252 -0
- package/src/ui/static/app.js +27 -0
- package/src/ui/static/htmx.min.js +1 -0
- package/src/ui/static/style.css +179 -0
- package/src/ui/strings.ts +73 -0
- package/src/ui/views.ts +315 -0
package/src/auth.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { appUrl, covers, reaches, threadPath, type McpToken } from "./config.ts";
|
|
3
|
+
import { NotFoundError, sha256, type Store } from "./store.ts";
|
|
4
|
+
import type { Actor, InboxerConfig, LoginLink, Scope, Session } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
/** The MCP token in `Authorization: Bearer <token>`, or null. Every token is compared in constant time. */
|
|
7
|
+
export function matchBearer(header: string | undefined, tokens: McpToken[]): McpToken | null {
|
|
8
|
+
const match = /^Bearer\s+(\S+)$/i.exec(header ?? "");
|
|
9
|
+
if (!match) return null;
|
|
10
|
+
const presented = createHash("sha256").update(match[1]!).digest();
|
|
11
|
+
let found: McpToken | null = null;
|
|
12
|
+
for (const entry of tokens) {
|
|
13
|
+
const expected = createHash("sha256").update(entry.token).digest();
|
|
14
|
+
if (timingSafeEqual(presented, expected)) found = entry;
|
|
15
|
+
}
|
|
16
|
+
return found;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ClientInfo {
|
|
20
|
+
ip: string | null;
|
|
21
|
+
userAgent: string | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* One-time login links and the browser sessions they create. Only hashes are stored: a leaked
|
|
26
|
+
* database does not reveal a usable link or cookie.
|
|
27
|
+
*/
|
|
28
|
+
export class Access {
|
|
29
|
+
private readonly store: Store;
|
|
30
|
+
private readonly cfg: InboxerConfig;
|
|
31
|
+
|
|
32
|
+
constructor(store: Store, cfg: InboxerConfig) {
|
|
33
|
+
this.store = store;
|
|
34
|
+
this.cfg = cfg;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The session the link creates reaches the actor's mailboxes. `threadId` makes it open that thread after signing in. */
|
|
38
|
+
async createLoginLink(actor: Actor, label: string | null, threadId: string | null = null): Promise<{ url: string; expires_at: string }> {
|
|
39
|
+
if (threadId && !reaches(actor.scope, (await this.store.requireThread(threadId)).mailbox)) throw new NotFoundError(`Thread ${threadId} not found`);
|
|
40
|
+
const token = randomBytes(32).toString("base64url");
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
const link: LoginLink = {
|
|
43
|
+
created_at: new Date(now).toISOString(),
|
|
44
|
+
expires_at: new Date(now + this.cfg.ui.loginLinkTtlMin * 60_000).toISOString(),
|
|
45
|
+
created_by: actor.name,
|
|
46
|
+
label,
|
|
47
|
+
next: threadId ? threadPath(threadId) : null,
|
|
48
|
+
scope: actor.scope,
|
|
49
|
+
};
|
|
50
|
+
await this.store.serialize(async () => {
|
|
51
|
+
await this.store.putLoginLink(sha256(token), link);
|
|
52
|
+
await this.store.audit("login_link.create", actor, null, { label });
|
|
53
|
+
});
|
|
54
|
+
return { url: appUrl(this.cfg, `/auth/${token}`), expires_at: link.expires_at };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async isLinkValid(token: string): Promise<boolean> {
|
|
58
|
+
const link = await this.store.getLoginLink(sha256(token));
|
|
59
|
+
return !!link && link.expires_at > new Date().toISOString();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Check-and-delete runs inside the write queue, so only one caller can turn a link into a session. */
|
|
63
|
+
consumeLoginLink(token: string, client: ClientInfo): Promise<{ secret: string; next: string } | null> {
|
|
64
|
+
const hash = sha256(token);
|
|
65
|
+
return this.store.serialize(async () => {
|
|
66
|
+
const link = await this.store.getLoginLink(hash);
|
|
67
|
+
if (!link) return null;
|
|
68
|
+
await this.store.deleteLoginLink(hash);
|
|
69
|
+
if (link.expires_at <= new Date().toISOString()) return null;
|
|
70
|
+
|
|
71
|
+
const secret = randomBytes(32).toString("base64url");
|
|
72
|
+
const now = new Date().toISOString();
|
|
73
|
+
const session: Session = {
|
|
74
|
+
id: sha256(secret),
|
|
75
|
+
created_at: now,
|
|
76
|
+
last_seen: now,
|
|
77
|
+
user_agent: client.userAgent,
|
|
78
|
+
ip: client.ip,
|
|
79
|
+
label: link.label,
|
|
80
|
+
created_by: link.created_by,
|
|
81
|
+
scope: link.scope,
|
|
82
|
+
};
|
|
83
|
+
await this.store.putSession(session);
|
|
84
|
+
await this.store.audit("login_link.use", { kind: "ui", name: session.id.slice(0, 12), scope: session.scope }, null, {
|
|
85
|
+
ip: client.ip,
|
|
86
|
+
user_agent: client.userAgent,
|
|
87
|
+
created_by: link.created_by,
|
|
88
|
+
});
|
|
89
|
+
return { secret, next: link.next ?? "/" };
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async authenticate(secret: string): Promise<Session | null> {
|
|
94
|
+
const session = await this.store.getSession(sha256(secret));
|
|
95
|
+
if (!session) return null;
|
|
96
|
+
session.last_seen = new Date().toISOString();
|
|
97
|
+
await this.store.serialize(async () => {
|
|
98
|
+
if (await this.store.getSession(session.id)) await this.store.putSession(session);
|
|
99
|
+
});
|
|
100
|
+
return session;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Sessions whose mailboxes `scope` reaches. */
|
|
104
|
+
async listSessions(scope: Scope): Promise<Session[]> {
|
|
105
|
+
return (await this.store.allSessions())
|
|
106
|
+
.filter(s => covers(scope, s.scope))
|
|
107
|
+
.sort((a, b) => b.last_seen.localeCompare(a.last_seen));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
revokeSession(id: string, actor: Actor, action = "session.revoke"): Promise<boolean> {
|
|
111
|
+
return this.store.serialize(async () => {
|
|
112
|
+
const session = await this.store.getSession(id);
|
|
113
|
+
if (!session || !covers(actor.scope, session.scope)) return false;
|
|
114
|
+
await this.store.deleteSession(id);
|
|
115
|
+
await this.store.audit(action, actor, id);
|
|
116
|
+
return true;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
import { CATCHALL, type InboxerConfig, type Scope } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
/** Absolute URL of an app path under `publicUrl`. */
|
|
5
|
+
export function appUrl(cfg: Pick<InboxerConfig, "publicUrl">, path: string): string {
|
|
6
|
+
return cfg.publicUrl.replace(/\/$/, "") + path;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** UI path of a thread, scrolled to one of its drafts when given. */
|
|
10
|
+
export function threadPath(threadId: string, draftId?: string): string {
|
|
11
|
+
return `/threads/${encodeURIComponent(threadId)}` + (draftId ? `#draft-${encodeURIComponent(draftId)}` : "");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fail(path: string, expected: string): never {
|
|
15
|
+
throw new Error(`Invalid inboxer config: ${path} must be ${expected}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function requireString(value: unknown, path: string): void {
|
|
19
|
+
if (typeof value !== "string" || !value) fail(path, "a non-empty string");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function requirePositive(value: unknown, path: string): void {
|
|
23
|
+
if (typeof value !== "number" || !(value > 0)) fail(path, "a positive number");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Asserts the shape `createInboxer` relies on. */
|
|
27
|
+
export function assertConfig(cfg: InboxerConfig, { requireProvider }: { requireProvider: boolean }): void {
|
|
28
|
+
requireString(cfg.publicUrl, "publicUrl");
|
|
29
|
+
requireString(cfg.dataDir, "dataDir");
|
|
30
|
+
if (!isAbsolute(cfg.dataDir)) fail("dataDir", "an absolute path");
|
|
31
|
+
requirePositive(cfg.syncIntervalMin, "syncIntervalMin");
|
|
32
|
+
requirePositive(cfg.threadWindowDays, "threadWindowDays");
|
|
33
|
+
|
|
34
|
+
if (!cfg.mailboxes || typeof cfg.mailboxes !== "object") fail("mailboxes", "an object keyed by mailbox id");
|
|
35
|
+
if (CATCHALL in cfg.mailboxes) fail(`mailboxes.${CATCHALL}`, "absent (the id is reserved)");
|
|
36
|
+
for (const [id, mailbox] of Object.entries(cfg.mailboxes)) {
|
|
37
|
+
requireString(mailbox.address, `mailboxes.${id}.address`);
|
|
38
|
+
requireString(mailbox.name, `mailboxes.${id}.name`);
|
|
39
|
+
if (mailbox.tokens !== undefined && (!mailbox.tokens || typeof mailbox.tokens !== "object")) fail(`mailboxes.${id}.tokens`, "an object of named tokens");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (requireProvider) requireString(cfg.provider?.type, "provider.type");
|
|
43
|
+
if (!cfg.mcp?.tokens || typeof cfg.mcp.tokens !== "object") fail("mcp.tokens", "an object of named tokens");
|
|
44
|
+
for (const [name, token] of Object.entries(cfg.mcp.tokens)) requireString(token, `mcp.tokens.${name}`);
|
|
45
|
+
mcpTokens(cfg);
|
|
46
|
+
requirePositive(cfg.mcp.maxAttachmentMb, "mcp.maxAttachmentMb");
|
|
47
|
+
requireString(cfg.ui?.cookieSecret, "ui.cookieSecret");
|
|
48
|
+
requirePositive(cfg.ui?.loginLinkTtlMin, "ui.loginLinkTtlMin");
|
|
49
|
+
requirePositive(cfg.ui?.undoSec, "ui.undoSec");
|
|
50
|
+
requirePositive(cfg.ui?.maxUploadMb, "ui.maxUploadMb");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface McpToken {
|
|
54
|
+
name: string;
|
|
55
|
+
token: string;
|
|
56
|
+
scope: Scope;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Tokens in `mcp.tokens` reach every mailbox; tokens under `mailboxes.<id>.tokens` reach only that
|
|
61
|
+
* mailbox. The same name and token under several mailboxes reach all of them.
|
|
62
|
+
*/
|
|
63
|
+
export function mcpTokens(cfg: InboxerConfig): McpToken[] {
|
|
64
|
+
const byName = new Map<string, McpToken>();
|
|
65
|
+
const add = (name: string, token: unknown, mailbox: string | null, path: string) => {
|
|
66
|
+
requireString(token, path);
|
|
67
|
+
const known = byName.get(name);
|
|
68
|
+
if (known && known.token !== token) fail(path, `the same token as every other entry named "${name}"`);
|
|
69
|
+
for (const other of byName.values()) {
|
|
70
|
+
if (other.name !== name && other.token === token) fail(path, `a token not already used by "${other.name}"`);
|
|
71
|
+
}
|
|
72
|
+
const entry = known ?? { name, token: token as string, scope: [] };
|
|
73
|
+
if (mailbox === null) entry.scope = null;
|
|
74
|
+
else if (entry.scope && !entry.scope.includes(mailbox)) entry.scope.push(mailbox);
|
|
75
|
+
byName.set(name, entry);
|
|
76
|
+
};
|
|
77
|
+
for (const [name, token] of Object.entries(cfg.mcp.tokens)) add(name, token, null, `mcp.tokens.${name}`);
|
|
78
|
+
for (const [id, mailbox] of Object.entries(cfg.mailboxes)) {
|
|
79
|
+
for (const [name, token] of Object.entries(mailbox.tokens ?? {})) add(name, token, id, `mailboxes.${id}.tokens.${name}`);
|
|
80
|
+
}
|
|
81
|
+
return [...byName.values()];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether `scope` reaches `mailbox`. */
|
|
85
|
+
export function reaches(scope: Scope, mailbox: string): boolean {
|
|
86
|
+
return scope === null || scope.includes(mailbox);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether `outer` reaches every mailbox `inner` does. */
|
|
90
|
+
export function covers(outer: Scope, inner: Scope): boolean {
|
|
91
|
+
return outer === null || (inner !== null && inner.every(m => outer.includes(m)));
|
|
92
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. */
|
|
2
|
+
export function bareAddress(value: string): string {
|
|
3
|
+
const match = /<([^<>]+)>\s*$/.exec(value);
|
|
4
|
+
return (match ? match[1]! : value).trim().toLowerCase();
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function formatAddress(name: string, address: string): string {
|
|
8
|
+
return `"${name.replace(/["\\]/g, "\\$&")}" <${address}>`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Splits a comma-separated recipient field, keeping commas inside quoted names. */
|
|
12
|
+
export function splitAddresses(value: string): string[] {
|
|
13
|
+
return (value.match(/("[^"]*"|[^,])+/g) ?? []).map(part => part.trim()).filter(Boolean);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function domainOf(address: string): string {
|
|
17
|
+
const bare = bareAddress(address);
|
|
18
|
+
return bare.slice(bare.lastIndexOf("@") + 1);
|
|
19
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Inbound attachment bytes on disk, under `<dataDir>/attachments/<message id>/`, so they outlive the provider's retention. */
|
|
6
|
+
export class AttachmentFiles {
|
|
7
|
+
private readonly dir: string;
|
|
8
|
+
|
|
9
|
+
constructor(dataDir: string) {
|
|
10
|
+
this.dir = join(dataDir, "attachments");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
private path(messageId: string, attachmentId: string): string {
|
|
14
|
+
return join(this.dir, messageId, createHash("sha1").update(attachmentId).digest("hex"));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async read(messageId: string, attachmentId: string): Promise<Uint8Array | null> {
|
|
18
|
+
try {
|
|
19
|
+
return await readFile(this.path(messageId, attachmentId));
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Writes through a temporary file, so a crash never leaves a partial attachment behind. */
|
|
27
|
+
async write(messageId: string, attachmentId: string, body: Uint8Array): Promise<void> {
|
|
28
|
+
const target = this.path(messageId, attachmentId);
|
|
29
|
+
await mkdir(join(this.dir, messageId), { recursive: true });
|
|
30
|
+
await writeFile(`${target}.tmp`, body);
|
|
31
|
+
await rename(`${target}.tmp`, target);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Actor, Context, MetaValue } from "../types.ts";
|
|
2
|
+
|
|
3
|
+
export interface ContextPatch {
|
|
4
|
+
/** Keys to set; `null` removes a key. Keys not mentioned are kept. */
|
|
5
|
+
meta?: Record<string, MetaValue | null>;
|
|
6
|
+
/** `null` clears the note. */
|
|
7
|
+
note?: string | null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function mergeContext(existing: Context | null, patch: ContextPatch, actor: Actor): Context {
|
|
11
|
+
const meta = { ...(existing?.meta ?? {}) };
|
|
12
|
+
for (const [key, value] of Object.entries(patch.meta ?? {})) {
|
|
13
|
+
if (value === null) delete meta[key];
|
|
14
|
+
else meta[key] = value;
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
meta,
|
|
18
|
+
note: patch.note !== undefined ? patch.note : (existing?.note ?? null),
|
|
19
|
+
updated_at: new Date().toISOString(),
|
|
20
|
+
updated_by: `${actor.kind}:${actor.name}`,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Every pair must be present. Values compare as text, so `991` matches `"991"`. */
|
|
25
|
+
export function metaMatches(meta: Record<string, MetaValue> | undefined, wanted: Record<string, MetaValue>): boolean {
|
|
26
|
+
if (!meta) return false;
|
|
27
|
+
return Object.entries(wanted).every(([key, value]) => key in meta && String(meta[key]) === String(value));
|
|
28
|
+
}
|