Skip to content

Commit ad159e0

Browse files
committed
feat(runtime): a script body sends mail and adds a timeline entry through platform doors that stamp who sent it
A sandboxed hook, action or job body gains two doors, each behind its own capability token: - `email.send` -> `ctx.email.send(input)`: the message goes through the mail service. The sender is the deployment's configured address, with a display name naming the calling user beside the organization; the sending user and the organization are stamped by the platform. At most 50 recipients per message, and at most OS_EMAIL_APP_SEND_HOURLY_LIMIT (default 200) caller-sent messages per organization per hour. - `activity.append` -> `ctx.activity.append(input)`: one entry on a record's activity timeline, written by the activity feed's owner. The actor, the organization and the origin (`<package>/<kind>:<name>`, new readonly `sys_activity.origin` column) are stamped by the platform; the values only the platform records are refused. Every record a door is pointed at is read in the caller's scope first. The mail bounds are one implementation shared with the HTTP send door. An outbox row the mail service did not write is sent as the configured sender. Clause-②: yes (widening) Metadata-protocol: added Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwV8gsjrvCXCqKoaiG
1 parent c04aa29 commit ad159e0

23 files changed

Lines changed: 1168 additions & 129 deletions

‎packages/cli/src/utils/extract-hook-body.ts‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
505505
},
506506
];
507507

508-
const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' }> = [
508+
const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [
509509
// Match `ctx.api.object(...)` directly OR a local alias like
510510
// `const api = ctx.api;` then `api.object(...)`. We accept any
511511
// identifier (or chain) ending in `.object(...)` followed by a known
@@ -535,6 +535,9 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
535535
// arrives as a sandbox refusal at run time, far from its cause. Over-inferring
536536
// grants a token the body may not use, which the sandbox simply never checks.
537537
{ rx: /\.\s*title\s*\(\s*[^)\s]/, cap: 'api.read' },
538+
// The two platform doors: a call to the door is what its token grants.
539+
{ rx: /ctx\.email\.send\b/, cap: 'email.send' },
540+
{ rx: /ctx\.activity\.append\b/, cap: 'activity.append' },
538541
];
539542

540543
export interface ExtractedBody {
@@ -546,7 +549,7 @@ export interface ExtractedBody {
546549
* is retired (see this file's header). An author whose needs differ from what
547550
* inference derives writes `body.capabilities` on the hook instead.
548551
*/
549-
capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log'>;
552+
capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>;
550553
/** True when source is a single expression (arrow with implicit return). */
551554
isExpression: boolean;
552555
}
@@ -740,10 +743,10 @@ interface ParameterRebind {
740743
/** Names bound to the WHOLE context: an identifier parameter, an object-rest element. */
741744
contextRoots: readonly string[];
742745
/** Names bound to ONE capability-bearing member: `({ log: l })` binds `l` to `ctx.log`. */
743-
memberLocals: Readonly<Record<'log' | 'crypto' | 'title', readonly string[]>>;
746+
memberLocals: Readonly<Record<'log' | 'crypto' | 'title' | 'email' | 'activity', readonly string[]>>;
744747
}
745748

746-
const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocals: { log: [], crypto: [], title: [] } };
749+
const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocals: { log: [], crypto: [], title: [], email: [], activity: [] } };
747750

748751
/**
749752
* The context members {@link CAPABILITY_PATTERNS} infers a token from. A
@@ -752,7 +755,7 @@ const NO_REBIND: ParameterRebind = { prologue: '', contextRoots: [], memberLocal
752755
* computed key under one of them could not be followed, and a body the build
753756
* under-grants is refused by the sandbox at run time.
754757
*/
755-
const CAPABILITY_BEARING_MEMBERS: ReadonlySet<string> = new Set(['api', 'log', 'crypto', 'title']);
758+
const CAPABILITY_BEARING_MEMBERS: ReadonlySet<string> = new Set(['api', 'log', 'crypto', 'title', 'email', 'activity']);
756759

757760
/**
758761
* A hook-face refusal that names the PARAMETER, in the family's wording: what
@@ -863,7 +866,7 @@ function planHookParameterRebind(
863866
}
864867

865868
const contextRoots: string[] = [];
866-
const memberLocals: Record<'log' | 'crypto' | 'title', string[]> = { log: [], crypto: [], title: [] };
869+
const memberLocals: Record<'log' | 'crypto' | 'title' | 'email' | 'activity', string[]> = { log: [], crypto: [], title: [], email: [], activity: [] };
867870
if (ts.isIdentifier(name)) {
868871
contextRoots.push(name.text);
869872
} else if (ts.isObjectBindingPattern(name)) {
@@ -890,7 +893,7 @@ function planHookParameterRebind(
890893
`(\`{ ${key ?? 'log'} }\`), or read it as \`ctx.${key ?? 'log'}\``,
891894
);
892895
}
893-
if (key !== 'api') memberLocals[key as 'log' | 'crypto' | 'title'].push(el.name.text);
896+
if (key !== 'api') memberLocals[key as 'log' | 'crypto' | 'title' | 'email' | 'activity'].push(el.name.text);
894897
}
895898
}
896899

@@ -963,13 +966,21 @@ function reboundCapabilities(source: string, rebind: ParameterRebind): Array<Ext
963966
for (const r of rebind.contextRoots) {
964967
if (new RegExp(String.raw`${root(r)}\.log\.(?:info|warn|error|debug)\b`).test(source)) out.push('log');
965968
if (new RegExp(String.raw`${root(r)}\.crypto\.randomUUID\b`).test(source)) out.push('crypto.uuid');
969+
if (new RegExp(String.raw`${root(r)}\.email\.send\b`).test(source)) out.push('email.send');
970+
if (new RegExp(String.raw`${root(r)}\.activity\.append\b`).test(source)) out.push('activity.append');
966971
}
967972
for (const l of rebind.memberLocals.log) {
968973
if (new RegExp(String.raw`${root(l)}\.(?:info|warn|error|debug)\b`).test(source)) out.push('log');
969974
}
970975
for (const l of rebind.memberLocals.crypto) {
971976
if (new RegExp(String.raw`${root(l)}\.randomUUID\b`).test(source)) out.push('crypto.uuid');
972977
}
978+
for (const l of rebind.memberLocals.email) {
979+
if (new RegExp(String.raw`${root(l)}\.send\b`).test(source)) out.push('email.send');
980+
}
981+
for (const l of rebind.memberLocals.activity) {
982+
if (new RegExp(String.raw`${root(l)}\.append\b`).test(source)) out.push('activity.append');
983+
}
973984
for (const l of rebind.memberLocals.title) {
974985
if (new RegExp(String.raw`${root(l)}\s*\(\s*[^)\s]`).test(source)) out.push('api.read');
975986
}
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The bounds a caller's message passes before the mail service sends it, for
5+
* every door a caller reaches mail through: the HTTP send door
6+
* (`POST /api/v1/email/send`, `@objectstack/rest`) and the script-body door
7+
* (`ctx.email.send`, `@objectstack/runtime`). One implementation, so the two
8+
* doors cannot admit different messages.
9+
*
10+
* What a door decides itself, before it calls this: WHO may use it (the HTTP
11+
* door's capability; the body door's declared `email.send` token) and what
12+
* shape a body may have. What this module decides, for both:
13+
*
14+
* 1. ATTRIBUTION — `sentBy` is the calling user. A message naming another
15+
* user is refused; one naming the caller (or none) is stamped with the
16+
* caller. A call with no calling user (a scheduled job's body) records no
17+
* sender, and a message naming one is refused.
18+
* 2. SENDER — the envelope sender is the deployment's configured sender
19+
* (`IEmailService.getDefaultFrom`). A `from` naming any other address is
20+
* refused; one naming the configured address is replaced by the configured
21+
* value. A deployment that reports no configured sender refuses a caller
22+
* `from`. Custom `headers` may not name the sender
23+
* ({@link SENDER_HEADER_NAMES}), and are accepted in one shape only: a
24+
* plain object mapping each header field name to a single-line string.
25+
* 3. TENANT — the message belongs to the caller's organization, which this
26+
* stamps as `organizationId`. A message naming another organization, or
27+
* naming one when the caller has none, is refused. `identityMail` is
28+
* refused: identity mail is sent by the server itself. A message restating
29+
* `identityMail: false` is admitted, and the forwarded message never
30+
* carries the caller's value.
31+
*
32+
* `replyTo` is not bounded: it is the caller's choice of Reply-To address and
33+
* makes no claim about the sender.
34+
*/
35+
36+
import type { EmailAddress } from '@objectstack/spec/contracts';
37+
38+
/**
39+
* Custom header names (compared case-insensitively) a caller may not set: each
40+
* one states who the message is from, which bound 2 reserves to the configured
41+
* sender.
42+
*/
43+
export const SENDER_HEADER_NAMES: ReadonlySet<string> = new Set(['from', 'sender', 'return-path']);
44+
45+
/**
46+
* A header field name: one or more printable US-ASCII characters other than
47+
* the colon (RFC 5322 §2.2).
48+
*/
49+
const HEADER_FIELD_NAME = /^[\x21-\x39\x3b-\x7e]+$/;
50+
51+
/** A plain object — an object literal or a JSON-parsed object, never an array or a class instance. */
52+
export function isPlainMailObject(value: unknown): value is Record<string, unknown> {
53+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
54+
const proto = Object.getPrototypeOf(value);
55+
return proto === Object.prototype || proto === null;
56+
}
57+
58+
/**
59+
* Why a caller's `headers` cannot be forwarded, or `undefined` when it can.
60+
* Absent is fine. Otherwise it must be the contract's `Record<string, string>`
61+
* exactly, with no key one of {@link SENDER_HEADER_NAMES}.
62+
*/
63+
function headersRefusal(headers: unknown): string | undefined {
64+
if (headers === undefined) return undefined;
65+
if (!isPlainMailObject(headers)) {
66+
return 'Custom `headers` must be an object mapping each header name to a string value.';
67+
}
68+
for (const [name, value] of Object.entries(headers)) {
69+
if (!HEADER_FIELD_NAME.test(name)) {
70+
return 'Custom `headers` must be keyed by header field names: printable ASCII with no space, control character or colon.';
71+
}
72+
if (typeof value !== 'string' || /[\r\n]/.test(value)) {
73+
return `Custom \`headers\` value for \`${name}\` must be a single-line string.`;
74+
}
75+
if (SENDER_HEADER_NAMES.has(name.toLowerCase())) {
76+
return `Custom header \`${name}\` cannot be set: the sender is the deployment's configured sender.`;
77+
}
78+
}
79+
return undefined;
80+
}
81+
82+
/**
83+
* The bare address an {@link EmailAddress} names, lower-cased for comparison,
84+
* or `undefined` when it names none. For the string form a trailing
85+
* `<address>` wins over the display name before it.
86+
*/
87+
export function mailAddressOf(value: unknown): string | undefined {
88+
let raw: unknown = value;
89+
if (value && typeof value === 'object') raw = (value as { address?: unknown }).address;
90+
if (typeof raw !== 'string') return undefined;
91+
const angled = /<([^<>]*)>\s*$/.exec(raw);
92+
const address = (angled ? angled[1] : raw).trim().toLowerCase();
93+
return address.length > 0 ? address : undefined;
94+
}
95+
96+
/** Who is sending, as the door resolved it — never as the message says. */
97+
export interface CallerMailIdentity {
98+
/** The calling user, or `undefined` for a call with none (a scheduled job). */
99+
userId: string | undefined;
100+
/** The caller's active organization, or `undefined` when it has none. */
101+
organizationId: string | undefined;
102+
}
103+
104+
/** The part of the mail service the bounds read: its configured sender. */
105+
export interface CallerMailSenderSource {
106+
getDefaultFrom?: () => EmailAddress | undefined;
107+
}
108+
109+
/** The bounded message, or the reason the caller's message is refused. */
110+
export type CallerMailBoundsResult =
111+
| { ok: true; input: Record<string, unknown> }
112+
| { ok: false; reason: string };
113+
114+
/**
115+
* Apply the three bounds of the module header to a caller's `message`, and
116+
* answer the message the mail service is handed, or the refusal. Pure: it
117+
* reads only its arguments and the service's configured sender.
118+
*/
119+
export function boundCallerMail(
120+
message: Record<string, unknown>,
121+
caller: CallerMailIdentity,
122+
sender: CallerMailSenderSource,
123+
): CallerMailBoundsResult {
124+
// Bound 1: attribution.
125+
if (message.sentBy !== undefined && message.sentBy !== caller.userId) {
126+
return {
127+
ok: false,
128+
reason: caller.userId
129+
? '`sentBy` is the authenticated caller; a send cannot be attributed to another user.'
130+
: '`sentBy` cannot be set: this call has no calling user. Omit it.',
131+
};
132+
}
133+
134+
// Bound 2: the sender is the configured one.
135+
const headersRefused = headersRefusal(message.headers);
136+
if (headersRefused !== undefined) return { ok: false, reason: headersRefused };
137+
let from: EmailAddress | undefined;
138+
if (message.from !== undefined) {
139+
const configured = typeof sender.getDefaultFrom === 'function' ? sender.getDefaultFrom() : undefined;
140+
const configuredAddress = mailAddressOf(configured);
141+
if (!configuredAddress || mailAddressOf(message.from) !== configuredAddress) {
142+
return {
143+
ok: false,
144+
reason: configuredAddress
145+
? `\`from\` must be the deployment's configured sender (${configuredAddress}); omit it to send as that sender.`
146+
: '`from` cannot be chosen by the caller: this deployment reports no configured sender. Configure one in Settings → Mail → From address and omit `from`.',
147+
};
148+
}
149+
from = configured;
150+
}
151+
152+
// Bound 3: the caller's organization, and identity mail is the server's.
153+
const organizationId = caller.organizationId;
154+
if (message.organizationId !== undefined && message.organizationId !== organizationId) {
155+
return {
156+
ok: false,
157+
reason: organizationId
158+
? '`organizationId` is the caller\'s active organization; a send cannot be recorded under another organization.'
159+
: '`organizationId` cannot be set: the caller has no active organization. Omit it.',
160+
};
161+
}
162+
if (message.identityMail !== undefined && message.identityMail !== false) {
163+
return {
164+
ok: false,
165+
reason: '`identityMail` cannot be set through this door: identity mail is sent by the server itself. Omit it.',
166+
};
167+
}
168+
169+
const rest = { ...message };
170+
delete rest.organizationId;
171+
delete rest.identityMail;
172+
delete rest.sentBy;
173+
return {
174+
ok: true,
175+
input: {
176+
...rest,
177+
...(caller.userId !== undefined ? { sentBy: caller.userId } : {}),
178+
...(organizationId !== undefined ? { organizationId } : {}),
179+
...(from !== undefined ? { from } : {}),
180+
},
181+
};
182+
}

‎packages/core/src/security/index.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,3 +704,15 @@ export {
704704
type AuthzGrantsCacheTtlReading,
705705
type AuthzPostureSink,
706706
} from './authz-cache-posture.js';
707+
708+
// The bounds a caller's message passes before the mail service sends it, shared
709+
// by the HTTP send door (rest) and the script-body door (runtime).
710+
export {
711+
boundCallerMail,
712+
mailAddressOf,
713+
isPlainMailObject,
714+
SENDER_HEADER_NAMES,
715+
type CallerMailIdentity,
716+
type CallerMailSenderSource,
717+
type CallerMailBoundsResult,
718+
} from './caller-mail-bounds.js';

0 commit comments

Comments
 (0)