@segmentstream/ontology 0.109.0 → 0.110.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/CHANGELOG.md +57 -0
- package/README.md +21 -0
- package/dist/analyze.js +55 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/manifest.d.ts +94 -5
- package/dist/manifest.js +41 -6
- package/dist/migrate/apply.d.ts +4 -3
- package/dist/migrate/apply.js +8 -3
- package/dist/migrate/model.d.ts +46 -2
- package/dist/migrate/plan.js +1 -1
- package/dist/migrate/preview.js +2 -1
- package/dist/migrate/storage.d.ts +13 -1
- package/dist/migrate/storage.js +33 -1
- package/dist/runtime/agent-counters.d.ts +36 -0
- package/dist/runtime/agent-counters.js +84 -0
- package/dist/runtime/agent-web.d.ts +1 -1
- package/dist/runtime/agent-web.js +175 -3
- package/dist/runtime/batch.js +4 -6
- package/dist/runtime/history.d.ts +24 -0
- package/dist/runtime/history.js +35 -1
- package/dist/runtime/pipeline.js +3 -0
- package/dist/runtime/principals.d.ts +6 -0
- package/dist/runtime/principals.js +25 -6
- package/dist/runtime/reads.js +9 -2
- package/dist/runtime/sign-in-links.d.ts +10 -0
- package/dist/runtime/sign-in-links.js +26 -25
- package/dist/runtime/sql-runtime.d.ts +1 -1
- package/dist/runtime/sql-runtime.js +3 -2
- package/dist/runtime/writes.js +4 -6
- package/dist/runtime.d.ts +18 -0
- package/dist/service/agent/authentication.d.ts +3 -2
- package/dist/service/agent/authentication.js +2 -11
- package/dist/service/agent/bot-check.d.ts +42 -0
- package/dist/service/agent/bot-check.js +32 -0
- package/dist/service/agent/guest-sign-up.d.ts +140 -0
- package/dist/service/agent/guest-sign-up.js +545 -0
- package/dist/service/agent/protocol.d.ts +33 -1
- package/dist/service/agent/protocol.js +41 -1
- package/dist/service/agent/server.d.ts +17 -0
- package/dist/service/agent/server.js +42 -3
- package/dist/service/agent/web-tokens.d.ts +21 -3
- package/dist/service/agent/web-tokens.js +79 -6
- package/dist/service/authentication.d.ts +8 -1
- package/dist/service/authentication.js +26 -5
- package/dist/service/config.d.ts +10 -0
- package/dist/service/operations.d.ts +5 -0
- package/dist/service/runtime-contract.d.ts +124 -1
- package/dist/service/runtime-identity.d.ts +23 -0
- package/dist/service/runtime-identity.js +31 -0
- package/dist/service/schemas.d.ts +46 -2
- package/dist/service/service.js +27 -1
- package/dist/service/webhooks.d.ts +15 -0
- package/dist/service/webhooks.js +15 -4
- package/dist/sign-in.d.ts +29 -0
- package/dist/sign-in.js +8 -0
- package/package.json +1 -1
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Effect, Redacted, Result, Schema } from "effect";
|
|
3
|
+
import { HttpServerResponse } from "effect/unstable/http";
|
|
4
|
+
import { EMAIL_PATTERN } from "../../property.js";
|
|
5
|
+
import { requestNeonSignInLink } from "../../runtime/sign-in-links.js";
|
|
6
|
+
import { schemaIssues } from "../../runtime/validation.js";
|
|
7
|
+
import { BASE_PATH } from "../api.js";
|
|
8
|
+
import { NEON_AUTH_SESSION_COOKIE, } from "../authentication.js";
|
|
9
|
+
import { RequestId, errorBodyForWire } from "../errors.js";
|
|
10
|
+
import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, callerOfAccessToken, newSecret, publicOrigin, secretHash, } from "../oauth/protocol.js";
|
|
11
|
+
import { matchesWebsite } from "../../sign-in.js";
|
|
12
|
+
import { GuestEmailCodeRequest, GuestSignUpRequest, GuestUsageRequest } from "./protocol.js";
|
|
13
|
+
import { AGENT_WEB_CLIENT_ID, agentResource, personalChat, websiteHeaders, websiteOf, } from "./web-tokens.js";
|
|
14
|
+
/**
|
|
15
|
+
* A guest becomes a user by proving an email address, as anyone signs up by email in the app,
|
|
16
|
+
* through the app's own email sign-in. The website's chat asks for an address, and the ontology
|
|
17
|
+
* has the app's sign-in email it: the six-digit code to an address whose Neon Auth account
|
|
18
|
+
* receives codes, else a sign-in link, which also creates the account. Either way the answer is
|
|
19
|
+
* the same, so it reveals nothing about the address.
|
|
20
|
+
*
|
|
21
|
+
* - The code comes back from the website's chat; the ontology checks it with the app's sign-in and
|
|
22
|
+
* verifies the session it opens as it verifies any sign-in token.
|
|
23
|
+
* - The link signs in the browser that opens it on the app's origin, then lands on the ontology's
|
|
24
|
+
* `GET /api/ontology/agent/guests/link?nonce=…`, which reads that session, admits the user and
|
|
25
|
+
* returns to the guest's website with a single-use handoff in the fragment. Only the guest who
|
|
26
|
+
* asked for the link may take it, so a link opened in another browser signs the person up and
|
|
27
|
+
* hands nothing to that browser: someone who types another person's address into a website's
|
|
28
|
+
* chat never gets their account.
|
|
29
|
+
*
|
|
30
|
+
* Once the address is proven the guest becomes the user `signUp` created with it, or a new one,
|
|
31
|
+
* and their grant to the agent becomes that user's. Every refusal is a code alone: the website
|
|
32
|
+
* says it in its own words.
|
|
33
|
+
*/
|
|
34
|
+
/** Sign-in emails one guest may ask for an hour, and one address may be sent from guests. */
|
|
35
|
+
export const GUEST_EMAIL_CODES_PER_HOUR = 5;
|
|
36
|
+
/** Codes and handoffs one guest may try an hour; each code also allows only a few tries. */
|
|
37
|
+
export const GUEST_SIGN_UP_ATTEMPTS_PER_HOUR = 10;
|
|
38
|
+
/** Where an emailed link lands once it signed its browser in on the app's origin. */
|
|
39
|
+
export const GUEST_LINK_PATH = `${BASE_PATH}/agent/guests/link`;
|
|
40
|
+
/** How long a link works: as long as the app's sign-in links. */
|
|
41
|
+
export const GUEST_LINK_TTL_MS = 24 * 60 * 60 * 1000;
|
|
42
|
+
/** How long the handoff of an opened link waits for the guest's browser. */
|
|
43
|
+
export const GUEST_HANDOFF_TTL_MS = 10 * 60 * 1000;
|
|
44
|
+
/** The fragment key that carries a handoff to the guest's website, and the one for a refusal. */
|
|
45
|
+
export const GUEST_HANDOFF_FRAGMENT = "segmentstream_guest";
|
|
46
|
+
export const GUEST_ERROR_FRAGMENT = "segmentstream_guest_error";
|
|
47
|
+
const EMAIL_CODE_TIMEOUT_MS = 10_000;
|
|
48
|
+
/** The session cookie a sign-in sets, as `name=value`, from the answer's `Set-Cookie` headers. */
|
|
49
|
+
function sessionCookie(response) {
|
|
50
|
+
const cookies = typeof response.headers.getSetCookie === "function"
|
|
51
|
+
? response.headers.getSetCookie()
|
|
52
|
+
: (response.headers.get("set-cookie") ?? "").split(/,(?=\s*[^;=\s]+=)/);
|
|
53
|
+
for (const cookie of cookies) {
|
|
54
|
+
const pair = cookie.split(";")[0]?.trim() ?? "";
|
|
55
|
+
const separator = pair.indexOf("=");
|
|
56
|
+
const name = separator > 0 ? pair.slice(0, separator) : "";
|
|
57
|
+
if (name.endsWith("session_token") && pair.length > separator + 1) {
|
|
58
|
+
return pair;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* {@link EmailCodes} through the app's Neon Auth, server to server, as the app's sign-in page calls
|
|
65
|
+
* it, with the app's production origin, which Neon Auth trusts: the address gets the app's own
|
|
66
|
+
* sign-in email. A checked code opens a Neon Auth session, whose token the ontology verifies like
|
|
67
|
+
* any sign-in token, and the session is closed again: the browser holds none. A link is the app's
|
|
68
|
+
* sign-in link, which the platform's email webhook sends as it sends every one.
|
|
69
|
+
*/
|
|
70
|
+
export function neonEmailCodes(config) {
|
|
71
|
+
const fetcher = config.fetch ?? fetch;
|
|
72
|
+
const base = config.baseUrl.replace(/\/+$/, "");
|
|
73
|
+
const call = (path, init) => fetcher(`${base}${path}`, {
|
|
74
|
+
...init,
|
|
75
|
+
redirect: "error",
|
|
76
|
+
signal: AbortSignal.timeout(EMAIL_CODE_TIMEOUT_MS),
|
|
77
|
+
headers: { origin: config.origin, ...init.headers },
|
|
78
|
+
});
|
|
79
|
+
return {
|
|
80
|
+
async send(email) {
|
|
81
|
+
let response;
|
|
82
|
+
try {
|
|
83
|
+
response = await call("/email-otp/send-verification-otp", {
|
|
84
|
+
method: "POST",
|
|
85
|
+
headers: { "content-type": "application/json" },
|
|
86
|
+
body: JSON.stringify({ email, type: "sign-in" }),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
return { status: "unavailable", cause: error };
|
|
91
|
+
}
|
|
92
|
+
void response.body?.cancel().catch(() => undefined);
|
|
93
|
+
return response.ok
|
|
94
|
+
? { status: "sent" }
|
|
95
|
+
: response.status === 429
|
|
96
|
+
? { status: "limited" }
|
|
97
|
+
: response.status === 400 || response.status === 422
|
|
98
|
+
? { status: "invalid" }
|
|
99
|
+
: {
|
|
100
|
+
status: "unavailable",
|
|
101
|
+
cause: "Neon Auth refused to send the sign-in code.",
|
|
102
|
+
httpStatus: response.status,
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
async sendLink(email, callbackPath) {
|
|
106
|
+
const failure = await requestNeonSignInLink({ baseUrl: config.baseUrl, origin: config.origin, fetch: fetcher }, email, new URL(callbackPath, config.origin).href);
|
|
107
|
+
return failure === undefined
|
|
108
|
+
? { status: "sent" }
|
|
109
|
+
: { status: "unavailable", cause: `Neon Auth did not issue the sign-in link: ${failure}.` };
|
|
110
|
+
},
|
|
111
|
+
async verify(email, code) {
|
|
112
|
+
let response;
|
|
113
|
+
try {
|
|
114
|
+
response = await call("/sign-in/email-otp", {
|
|
115
|
+
method: "POST",
|
|
116
|
+
headers: { "content-type": "application/json" },
|
|
117
|
+
body: JSON.stringify({ email, otp: code }),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
return { status: "unavailable", cause: error };
|
|
122
|
+
}
|
|
123
|
+
void response.body?.cancel().catch(() => undefined);
|
|
124
|
+
if (response.status === 429) {
|
|
125
|
+
return { status: "limited" };
|
|
126
|
+
}
|
|
127
|
+
if (response.status === 400 || response.status === 401 || response.status === 403) {
|
|
128
|
+
return { status: "invalid" };
|
|
129
|
+
}
|
|
130
|
+
const cookie = response.ok ? sessionCookie(response) : undefined;
|
|
131
|
+
if (cookie === undefined) {
|
|
132
|
+
return {
|
|
133
|
+
status: "unavailable",
|
|
134
|
+
cause: "Neon Auth checked the code without opening a session.",
|
|
135
|
+
httpStatus: response.status,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const answer = await call("/token", { method: "GET", headers: { cookie } });
|
|
140
|
+
const body = (await answer.json().catch(() => undefined));
|
|
141
|
+
const token = answer.ok && typeof body?.token === "string" ? body.token : undefined;
|
|
142
|
+
if (token === undefined) {
|
|
143
|
+
return {
|
|
144
|
+
status: "unavailable",
|
|
145
|
+
cause: "Neon Auth gave the code's session no token.",
|
|
146
|
+
httpStatus: answer.status,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const verified = await config.verifyToken(token);
|
|
150
|
+
return verified.status === "valid" && verified.identity.provider === "neon-auth"
|
|
151
|
+
? { status: "verified", identity: verified.identity }
|
|
152
|
+
: {
|
|
153
|
+
status: "unavailable",
|
|
154
|
+
cause: `The code's session token did not verify: ${verified.status}.`,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
return { status: "unavailable", cause: error };
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
// The session served only to prove the address; nobody uses it.
|
|
162
|
+
await call("/sign-out", { method: "POST", headers: { cookie } })
|
|
163
|
+
.then((closed) => closed.body?.cancel())
|
|
164
|
+
.catch(() => undefined);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function bodyOf(request) {
|
|
170
|
+
return Effect.map(Effect.orDie(request.text), (text) => {
|
|
171
|
+
try {
|
|
172
|
+
return JSON.parse(text);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
function bearerOf(request) {
|
|
180
|
+
const match = /^Bearer\s+(\S+)$/iu.exec(request.headers.authorization?.trim() ?? "");
|
|
181
|
+
return match?.[1];
|
|
182
|
+
}
|
|
183
|
+
/** An address as the app's sign-in stores it: trimmed and lower case. */
|
|
184
|
+
function normalizedEmail(value) {
|
|
185
|
+
const email = value.trim().toLowerCase();
|
|
186
|
+
return EMAIL_PATTERN.test(email) ? email : undefined;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The page of a guest website a link returns to, without its fragment: an `https` address, or
|
|
190
|
+
* `http` on `localhost` and `127.0.0.1`, on one of the guests' websites. `undefined` for anything
|
|
191
|
+
* else.
|
|
192
|
+
*/
|
|
193
|
+
export function guestReturnTo(value, origins) {
|
|
194
|
+
const url = URL.canParse(value) ? new URL(value) : undefined;
|
|
195
|
+
const local = url?.hostname === "localhost" || url?.hostname === "127.0.0.1";
|
|
196
|
+
if (url === undefined ||
|
|
197
|
+
!(url.protocol === "https:" || (url.protocol === "http:" && local)) ||
|
|
198
|
+
url.username !== "" ||
|
|
199
|
+
url.password !== "" ||
|
|
200
|
+
!matchesWebsite(origins, url.origin)) {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
url.hash = "";
|
|
204
|
+
return url.href;
|
|
205
|
+
}
|
|
206
|
+
/** Where a link returns without a page of its own: the first guest website that is no pattern. */
|
|
207
|
+
function defaultReturnTo(origins) {
|
|
208
|
+
const origin = origins.find((candidate) => !candidate.includes("*"));
|
|
209
|
+
return origin === undefined ? undefined : `${origin}/`;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The routes a website's guest uses to become a user. The first two take the guest's agent token
|
|
213
|
+
* as their bearer, from a declared website:
|
|
214
|
+
*
|
|
215
|
+
* - `POST /api/ontology/agent/guests/email-code` with `{ email, return_to? }` has the app's sign-in
|
|
216
|
+
* email the address a code or a link, and answers `{ sent: true }` either way. `return_to` is the
|
|
217
|
+
* page of a guest website the link returns to.
|
|
218
|
+
* - `POST /api/ontology/agent/guests/sign-up` with `{ email, code }`, or with the `{ handoff }` an
|
|
219
|
+
* opened link gave the browser, makes the guest that user and answers
|
|
220
|
+
* `{ token, expires_at, refresh_token, chat, user_id, created }`: the user's agent token and
|
|
221
|
+
* refresh token, of the grant that was the guest's, and the user's own chat.
|
|
222
|
+
* - `GET /api/ontology/agent/guests/link?nonce=…` is where the link lands, signed in on the app's
|
|
223
|
+
* origin: it admits the user and redirects to `return_to` with `#segmentstream_guest=<handoff>`,
|
|
224
|
+
* or `#segmentstream_guest_error=<code>`.
|
|
225
|
+
*
|
|
226
|
+
* Refusals: `email_sign_up_closed` when `signUp` does not list `email`, `member_address` for an
|
|
227
|
+
* address of a user sign-up did not create, `code_invalid`, `link_invalid`, `handoff_invalid`,
|
|
228
|
+
* `handoff_other_browser` for a handoff minted for another guest, `rate_limited` with `Retry-After`,
|
|
229
|
+
* `email_unavailable` when the app's email sign-in cannot be reached, and `forbidden` for a guest
|
|
230
|
+
* who is gone.
|
|
231
|
+
*/
|
|
232
|
+
export function guestSignUpRoutes(options) {
|
|
233
|
+
const { emailSignUp, web, oauth, origins, emailCodes } = options;
|
|
234
|
+
/** Logs why the app's email sign-in could not answer, under the request's id. */
|
|
235
|
+
const logUnavailable = (requestId, operation, failure) => Effect.logError("ontology.agent.guest_email_unavailable", failure.cause).pipe(Effect.annotateLogs({
|
|
236
|
+
requestId,
|
|
237
|
+
operation,
|
|
238
|
+
...(failure.httpStatus === undefined ? {} : { status: failure.httpStatus }),
|
|
239
|
+
}));
|
|
240
|
+
/** Runs `answer` for the guest the bearer stands for, from a declared website. */
|
|
241
|
+
const asGuest = (answer) => (request) => Effect.gen(function* () {
|
|
242
|
+
const requestId = yield* RequestId;
|
|
243
|
+
const origin = websiteOf(request, origins);
|
|
244
|
+
const headers = {
|
|
245
|
+
"cache-control": "no-store",
|
|
246
|
+
...(origin === undefined ? { vary: "Origin" } : websiteHeaders(origin)),
|
|
247
|
+
};
|
|
248
|
+
const reply = (status, body, extra = {}) => Effect.succeed(HttpServerResponse.jsonUnsafe(body, { status, headers: { ...headers, ...extra } }));
|
|
249
|
+
const refuse = (error, status, extra = {}) => reply(status, errorBodyForWire({ error, detail: error, requestId }), extra);
|
|
250
|
+
if (origin === undefined) {
|
|
251
|
+
return yield* refuse("origin_not_allowed", 403);
|
|
252
|
+
}
|
|
253
|
+
const token = bearerOf(request);
|
|
254
|
+
const authenticated = token === undefined || !token.startsWith(ACCESS_TOKEN_PREFIX)
|
|
255
|
+
? undefined
|
|
256
|
+
: yield* callerOfAccessToken(oauth, token, agentResource(publicOrigin(request)));
|
|
257
|
+
if (authenticated === undefined) {
|
|
258
|
+
return yield* refuse("unauthorized", 401);
|
|
259
|
+
}
|
|
260
|
+
if (authenticated.principal.kind !== "guest" ||
|
|
261
|
+
authenticated.caller.kind !== "oauth" ||
|
|
262
|
+
authenticated.caller.client.id !== AGENT_WEB_CLIENT_ID) {
|
|
263
|
+
return yield* refuse("forbidden", 403);
|
|
264
|
+
}
|
|
265
|
+
return yield* answer({
|
|
266
|
+
guestId: authenticated.principal.id,
|
|
267
|
+
body: yield* bodyOf(request),
|
|
268
|
+
reply,
|
|
269
|
+
refuse,
|
|
270
|
+
requestId,
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
const limited = (scope, subject, limit) => web.countGuestAttempt === undefined
|
|
274
|
+
? Effect.succeed(undefined)
|
|
275
|
+
: web.countGuestAttempt({ scope, subject, limit });
|
|
276
|
+
const invalidBody = (requestId, issues) => errorBodyForWire({ error: "invalid_request", detail: "invalid_request", requestId, issues });
|
|
277
|
+
const upgraded = (reply, requestId, guestId, user) => Effect.gen(function* () {
|
|
278
|
+
yield* Effect.logInfo("ontology.agent.guest_signed_up").pipe(Effect.annotateLogs({ requestId, guestId, userId: user.userId, created: user.created }));
|
|
279
|
+
return yield* reply(200, {
|
|
280
|
+
token: user.token,
|
|
281
|
+
expires_at: user.expiresAt.toISOString(),
|
|
282
|
+
refresh_token: user.refreshToken,
|
|
283
|
+
chat: personalChat(user.userId),
|
|
284
|
+
user_id: user.userId,
|
|
285
|
+
created: user.created,
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
const emailCode = asGuest(({ guestId, body, reply, refuse, requestId }) => Effect.gen(function* () {
|
|
289
|
+
const decoded = Schema.decodeUnknownResult(GuestEmailCodeRequest)(body, {
|
|
290
|
+
errors: "all",
|
|
291
|
+
onExcessProperty: "error",
|
|
292
|
+
});
|
|
293
|
+
if (Result.isFailure(decoded)) {
|
|
294
|
+
return yield* reply(400, invalidBody(requestId, schemaIssues(decoded.failure)));
|
|
295
|
+
}
|
|
296
|
+
const email = normalizedEmail(decoded.success.email);
|
|
297
|
+
const returnTo = decoded.success.return_to === undefined
|
|
298
|
+
? undefined
|
|
299
|
+
: guestReturnTo(decoded.success.return_to, origins);
|
|
300
|
+
if (email === undefined || (decoded.success.return_to !== undefined && !returnTo)) {
|
|
301
|
+
return yield* refuse("invalid_request", 400);
|
|
302
|
+
}
|
|
303
|
+
if (!emailSignUp) {
|
|
304
|
+
return yield* refuse("email_sign_up_closed", 403);
|
|
305
|
+
}
|
|
306
|
+
if (emailCodes === undefined) {
|
|
307
|
+
return yield* refuse("email_unavailable", 503);
|
|
308
|
+
}
|
|
309
|
+
const address = createHash("sha256").update(email).digest("hex");
|
|
310
|
+
for (const subject of [`guest:${guestId}`, `email:${address}`]) {
|
|
311
|
+
const retryAfter = yield* limited("guestEmailCodesPerHour", subject, GUEST_EMAIL_CODES_PER_HOUR);
|
|
312
|
+
if (retryAfter !== undefined) {
|
|
313
|
+
return yield* refuse("rate_limited", 429, { "retry-after": String(retryAfter) });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// Neon Auth sends codes only to its existing accounts; anyone else gets a link, which also
|
|
317
|
+
// creates the account. The answer is the same either way.
|
|
318
|
+
const method = web.guestEmailMethod === undefined ? "code" : yield* web.guestEmailMethod(email);
|
|
319
|
+
let sent;
|
|
320
|
+
if (method === "code") {
|
|
321
|
+
sent = yield* Effect.promise(() => emailCodes.send(email));
|
|
322
|
+
}
|
|
323
|
+
else if (web.requestGuestLink === undefined) {
|
|
324
|
+
sent = { status: "unavailable", cause: "This runtime stores no guest sign-in links." };
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
const nonce = newSecret();
|
|
328
|
+
yield* web.requestGuestLink({
|
|
329
|
+
guestId,
|
|
330
|
+
email,
|
|
331
|
+
returnTo,
|
|
332
|
+
nonceHash: secretHash(nonce),
|
|
333
|
+
expiresAt: new Date(Date.now() + GUEST_LINK_TTL_MS),
|
|
334
|
+
});
|
|
335
|
+
sent = yield* Effect.promise(() => emailCodes.sendLink(email, `${GUEST_LINK_PATH}?nonce=${encodeURIComponent(nonce)}`));
|
|
336
|
+
}
|
|
337
|
+
switch (sent.status) {
|
|
338
|
+
case "sent":
|
|
339
|
+
return yield* reply(200, { sent: true });
|
|
340
|
+
case "invalid":
|
|
341
|
+
return yield* refuse("invalid_request", 400);
|
|
342
|
+
case "limited":
|
|
343
|
+
return yield* refuse("rate_limited", 429, { "retry-after": "60" });
|
|
344
|
+
case "unavailable":
|
|
345
|
+
yield* logUnavailable(requestId, method === "code" ? "send_code" : "send_link", sent);
|
|
346
|
+
return yield* refuse("email_unavailable", 503);
|
|
347
|
+
}
|
|
348
|
+
}));
|
|
349
|
+
const signUp = asGuest(({ guestId, body, reply, refuse, requestId }) => Effect.gen(function* () {
|
|
350
|
+
const decoded = Schema.decodeUnknownResult(GuestSignUpRequest)(body, {
|
|
351
|
+
errors: "all",
|
|
352
|
+
onExcessProperty: "error",
|
|
353
|
+
});
|
|
354
|
+
if (Result.isFailure(decoded)) {
|
|
355
|
+
return yield* reply(400, invalidBody(requestId, schemaIssues(decoded.failure)));
|
|
356
|
+
}
|
|
357
|
+
if (!emailSignUp) {
|
|
358
|
+
return yield* refuse("email_sign_up_closed", 403);
|
|
359
|
+
}
|
|
360
|
+
const retryAfter = yield* limited("guestSignUpAttemptsPerHour", `guest:${guestId}`, GUEST_SIGN_UP_ATTEMPTS_PER_HOUR);
|
|
361
|
+
if (retryAfter !== undefined) {
|
|
362
|
+
return yield* refuse("rate_limited", 429, { "retry-after": String(retryAfter) });
|
|
363
|
+
}
|
|
364
|
+
const expiresAt = new Date(Date.now() + ACCESS_TOKEN_TTL_MS);
|
|
365
|
+
if ("handoff" in decoded.success) {
|
|
366
|
+
if (web.takeGuestHandoff === undefined) {
|
|
367
|
+
return yield* refuse("handoff_invalid", 403);
|
|
368
|
+
}
|
|
369
|
+
const taken = yield* web.takeGuestHandoff({
|
|
370
|
+
handoffHash: secretHash(decoded.success.handoff),
|
|
371
|
+
guestId,
|
|
372
|
+
expiresAt,
|
|
373
|
+
});
|
|
374
|
+
switch (taken.status) {
|
|
375
|
+
case "upgraded":
|
|
376
|
+
return yield* upgraded(reply, requestId, guestId, taken);
|
|
377
|
+
case "handoff_invalid":
|
|
378
|
+
case "handoff_other_browser":
|
|
379
|
+
return yield* refuse(taken.status, 403);
|
|
380
|
+
case "refused":
|
|
381
|
+
return yield* refuse("forbidden", 403);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
const { email: given, code } = decoded.success;
|
|
385
|
+
const email = normalizedEmail(given);
|
|
386
|
+
if (email === undefined) {
|
|
387
|
+
return yield* refuse("invalid_request", 400);
|
|
388
|
+
}
|
|
389
|
+
if (emailCodes === undefined || web.upgradeGuest === undefined) {
|
|
390
|
+
return yield* refuse("email_unavailable", 503);
|
|
391
|
+
}
|
|
392
|
+
const checked = yield* Effect.promise(() => emailCodes.verify(email, code));
|
|
393
|
+
if (checked.status === "limited") {
|
|
394
|
+
return yield* refuse("rate_limited", 429, { "retry-after": "60" });
|
|
395
|
+
}
|
|
396
|
+
if (checked.status === "unavailable") {
|
|
397
|
+
yield* logUnavailable(requestId, "verify_code", checked);
|
|
398
|
+
return yield* refuse("email_unavailable", 503);
|
|
399
|
+
}
|
|
400
|
+
// The session must prove the very address the guest gave, verified by the sign-in.
|
|
401
|
+
if (checked.status === "invalid" || checked.identity.email?.trim().toLowerCase() !== email) {
|
|
402
|
+
return yield* refuse("code_invalid", 403);
|
|
403
|
+
}
|
|
404
|
+
const result = yield* web.upgradeGuest({ guestId, identity: checked.identity, expiresAt });
|
|
405
|
+
switch (result.status) {
|
|
406
|
+
case "upgraded":
|
|
407
|
+
return yield* upgraded(reply, requestId, guestId, result);
|
|
408
|
+
case "sign_up_closed":
|
|
409
|
+
return yield* refuse("email_sign_up_closed", 403);
|
|
410
|
+
case "member_address":
|
|
411
|
+
return yield* refuse("member_address", 403);
|
|
412
|
+
case "refused":
|
|
413
|
+
return yield* refuse("forbidden", 403);
|
|
414
|
+
}
|
|
415
|
+
}));
|
|
416
|
+
/** The identity of the app's session the request's cookie holds, verified as any sign-in. */
|
|
417
|
+
const sessionIdentity = (request) => Effect.promise(async () => {
|
|
418
|
+
const session = request.cookies[NEON_AUTH_SESSION_COOKIE];
|
|
419
|
+
if (options.exchangeSession === undefined || session === undefined || session === "") {
|
|
420
|
+
return undefined;
|
|
421
|
+
}
|
|
422
|
+
const exchanged = await options.exchangeSession(Redacted.make(session), publicOrigin(request));
|
|
423
|
+
if (exchanged.status !== "token") {
|
|
424
|
+
return exchanged.status === "unavailable" ? "unavailable" : undefined;
|
|
425
|
+
}
|
|
426
|
+
const verified = await options.verifyToken(exchanged.token);
|
|
427
|
+
return verified.status === "valid" && verified.identity.provider === "neon-auth"
|
|
428
|
+
? verified.identity
|
|
429
|
+
: verified.status === "unavailable"
|
|
430
|
+
? "unavailable"
|
|
431
|
+
: undefined;
|
|
432
|
+
});
|
|
433
|
+
/**
|
|
434
|
+
* `GET /api/ontology/agent/guests/link?nonce=…`: an emailed link, opened and signed in on the
|
|
435
|
+
* app's origin. It admits the user the link proves and returns to the guest's website with the
|
|
436
|
+
* handoff, which only that guest's browser may take, or with the refusal's code.
|
|
437
|
+
*/
|
|
438
|
+
const link = (request) => Effect.gen(function* () {
|
|
439
|
+
const requestId = yield* RequestId;
|
|
440
|
+
const back = (returnTo, fragment) => {
|
|
441
|
+
const target = returnTo ?? defaultReturnTo(origins);
|
|
442
|
+
return target === undefined
|
|
443
|
+
? HttpServerResponse.jsonUnsafe(errorBodyForWire({ error: "link_invalid", detail: "link_invalid", requestId }), { status: 400, headers: { "cache-control": "no-store" } })
|
|
444
|
+
: HttpServerResponse.empty({
|
|
445
|
+
status: 303,
|
|
446
|
+
headers: {
|
|
447
|
+
location: `${target}#${new URLSearchParams(fragment).toString()}`,
|
|
448
|
+
"cache-control": "no-store",
|
|
449
|
+
"referrer-policy": "no-referrer",
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
};
|
|
453
|
+
const refused = (code, returnTo) => back(returnTo, { [GUEST_ERROR_FRAGMENT]: code });
|
|
454
|
+
const url = URL.canParse(request.originalUrl)
|
|
455
|
+
? new URL(request.originalUrl)
|
|
456
|
+
: new URL(request.url, publicOrigin(request));
|
|
457
|
+
const nonce = url.searchParams.get("nonce") ?? "";
|
|
458
|
+
if (!/^[A-Za-z0-9_-]{16,256}$/.test(nonce)) {
|
|
459
|
+
return refused("link_invalid");
|
|
460
|
+
}
|
|
461
|
+
if (!emailSignUp) {
|
|
462
|
+
return refused("email_sign_up_closed");
|
|
463
|
+
}
|
|
464
|
+
const identity = yield* sessionIdentity(request);
|
|
465
|
+
if (identity === "unavailable" || web.openGuestLink === undefined) {
|
|
466
|
+
yield* logUnavailable(requestId, "open_link", {
|
|
467
|
+
status: "unavailable",
|
|
468
|
+
cause: identity === "unavailable"
|
|
469
|
+
? "The link's Neon Auth session could not be exchanged or verified."
|
|
470
|
+
: "This runtime stores no guest sign-in links.",
|
|
471
|
+
});
|
|
472
|
+
return refused("email_unavailable");
|
|
473
|
+
}
|
|
474
|
+
// Without the session the link set, nothing is taken: the link still works once signed in.
|
|
475
|
+
if (identity === undefined) {
|
|
476
|
+
return refused("link_invalid");
|
|
477
|
+
}
|
|
478
|
+
const handoff = newSecret();
|
|
479
|
+
const opened = yield* web.openGuestLink({
|
|
480
|
+
nonceHash: secretHash(nonce),
|
|
481
|
+
identity,
|
|
482
|
+
handoffHash: secretHash(handoff),
|
|
483
|
+
handoffExpiresAt: new Date(Date.now() + GUEST_HANDOFF_TTL_MS),
|
|
484
|
+
});
|
|
485
|
+
switch (opened.status) {
|
|
486
|
+
case "handed_off":
|
|
487
|
+
yield* Effect.logInfo("ontology.agent.guest_link_opened").pipe(Effect.annotateLogs({ requestId, created: opened.created }));
|
|
488
|
+
return back(opened.returnTo, { [GUEST_HANDOFF_FRAGMENT]: handoff });
|
|
489
|
+
case "refused":
|
|
490
|
+
return refused("forbidden", opened.returnTo);
|
|
491
|
+
default:
|
|
492
|
+
return refused(opened.status, opened.returnTo);
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
return { emailCode, signUp, link };
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* `OPTIONS` of the guests' routes: lets a browser on one of the guests' websites call them with
|
|
499
|
+
* the guest's agent token; any other origin gets no permission.
|
|
500
|
+
*/
|
|
501
|
+
export function guestRoutesPreflight(origins) {
|
|
502
|
+
return (request) => Effect.sync(() => {
|
|
503
|
+
const origin = websiteOf(request, origins);
|
|
504
|
+
return origin === undefined
|
|
505
|
+
? HttpServerResponse.empty({ status: 403, headers: { vary: "Origin" } })
|
|
506
|
+
: HttpServerResponse.empty({
|
|
507
|
+
status: 204,
|
|
508
|
+
headers: {
|
|
509
|
+
...websiteHeaders(origin),
|
|
510
|
+
"access-control-allow-methods": "POST",
|
|
511
|
+
"access-control-allow-headers": "authorization, content-type",
|
|
512
|
+
"access-control-max-age": "600",
|
|
513
|
+
},
|
|
514
|
+
});
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* `POST /api/ontology/agent/guests/usage` (runtime): adds the model cost of a guest's turn to the
|
|
519
|
+
* guests' spend, once per `key`, and answers 204.
|
|
520
|
+
*/
|
|
521
|
+
export function recordGuestUsage(web) {
|
|
522
|
+
return (request) => Effect.gen(function* () {
|
|
523
|
+
const requestId = yield* RequestId;
|
|
524
|
+
const decoded = Schema.decodeUnknownResult(GuestUsageRequest)(yield* bodyOf(request), {
|
|
525
|
+
errors: "all",
|
|
526
|
+
onExcessProperty: "error",
|
|
527
|
+
});
|
|
528
|
+
if (Result.isFailure(decoded)) {
|
|
529
|
+
return HttpServerResponse.jsonUnsafe(errorBodyForWire({
|
|
530
|
+
error: "invalid_request",
|
|
531
|
+
detail: "The request body is invalid.",
|
|
532
|
+
requestId,
|
|
533
|
+
issues: schemaIssues(decoded.failure),
|
|
534
|
+
}), { status: 400 });
|
|
535
|
+
}
|
|
536
|
+
if (web.recordGuestUsage !== undefined) {
|
|
537
|
+
yield* web.recordGuestUsage({
|
|
538
|
+
guestId: decoded.success.guest_id,
|
|
539
|
+
costUsd: decoded.success.cost_usd,
|
|
540
|
+
key: decoded.success.key,
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
return HttpServerResponse.empty({ status: 204, headers: { "cache-control": "no-store" } });
|
|
544
|
+
});
|
|
545
|
+
}
|
|
@@ -27,7 +27,8 @@ export declare const PairingRequest: Schema.Struct<{
|
|
|
27
27
|
}>;
|
|
28
28
|
/**
|
|
29
29
|
* The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
|
|
30
|
-
* `guest` limits guests' turns, apart from those of people who signed up
|
|
30
|
+
* `guest` limits guests' turns, apart from those of people who signed up, and, when the agent sets
|
|
31
|
+
* them, the model cost of each guest's turns and of every guest's together each day.
|
|
31
32
|
*/
|
|
32
33
|
export declare const AgentLimitsRequest: Schema.Struct<{
|
|
33
34
|
readonly perSender: Schema.optionalKey<Schema.Struct<{
|
|
@@ -39,8 +40,37 @@ export declare const AgentLimitsRequest: Schema.Struct<{
|
|
|
39
40
|
readonly guest: Schema.optionalKey<Schema.Struct<{
|
|
40
41
|
readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
|
|
41
42
|
readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
|
|
43
|
+
readonly usdPerDay: Schema.optionalKey<Schema.Number>;
|
|
44
|
+
readonly workspaceUsdPerDay: Schema.optionalKey<Schema.Number>;
|
|
42
45
|
}>>;
|
|
43
46
|
}>;
|
|
47
|
+
/**
|
|
48
|
+
* `POST /api/ontology/agent/guests/usage` (runtime): the model cost of a guest's turn, as the
|
|
49
|
+
* runtime recorded it, for the guests' money caps. `key` names the report, so a retry adds nothing.
|
|
50
|
+
*/
|
|
51
|
+
export declare const GuestUsageRequest: Schema.Struct<{
|
|
52
|
+
readonly guest_id: Schema.String;
|
|
53
|
+
readonly cost_usd: Schema.Number;
|
|
54
|
+
readonly key: Schema.String;
|
|
55
|
+
}>;
|
|
56
|
+
/**
|
|
57
|
+
* `POST /api/ontology/agent/guests/email-code`: the address a guest proves, and the page of the
|
|
58
|
+
* guest's website an emailed link returns to.
|
|
59
|
+
*/
|
|
60
|
+
export declare const GuestEmailCodeRequest: Schema.Struct<{
|
|
61
|
+
readonly email: Schema.String;
|
|
62
|
+
readonly return_to: Schema.optionalKey<Schema.String>;
|
|
63
|
+
}>;
|
|
64
|
+
/**
|
|
65
|
+
* `POST /api/ontology/agent/guests/sign-up`: the address and the code it received, or the handoff
|
|
66
|
+
* an opened link gave the guest's browser.
|
|
67
|
+
*/
|
|
68
|
+
export declare const GuestSignUpRequest: Schema.Union<readonly [Schema.Struct<{
|
|
69
|
+
readonly email: Schema.String;
|
|
70
|
+
readonly code: Schema.String;
|
|
71
|
+
}>, Schema.Struct<{
|
|
72
|
+
readonly handoff: Schema.String;
|
|
73
|
+
}>]>;
|
|
44
74
|
export declare const ResolveIdentityRequest: Schema.Struct<{
|
|
45
75
|
readonly chat: Schema.Literals<readonly ["private", "group"]>;
|
|
46
76
|
readonly turn: Schema.Boolean;
|
|
@@ -58,6 +88,8 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
|
|
|
58
88
|
readonly guest: Schema.optionalKey<Schema.Struct<{
|
|
59
89
|
readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
|
|
60
90
|
readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
|
|
91
|
+
readonly usdPerDay: Schema.optionalKey<Schema.Number>;
|
|
92
|
+
readonly workspaceUsdPerDay: Schema.optionalKey<Schema.Number>;
|
|
61
93
|
}>>;
|
|
62
94
|
}>>;
|
|
63
95
|
readonly provider: Schema.String;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomInt } from "node:crypto";
|
|
2
2
|
import { Schema } from "effect";
|
|
3
|
+
import { GUEST_USD_CEILINGS, MAX_GUEST_USAGE_REPORT_USD } from "../../runtime/agent-counters.js";
|
|
3
4
|
/** How long a member has to open the connect link, sign in and approve the pairing. */
|
|
4
5
|
export const PAIRING_TTL_MS = 10 * 60 * 1000;
|
|
5
6
|
/**
|
|
@@ -42,9 +43,14 @@ export const PairingRequest = Schema.Struct({
|
|
|
42
43
|
});
|
|
43
44
|
/** Trusted runtime resolution: channel admission and limits run before expensive processing. */
|
|
44
45
|
const PositiveLimit = Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_000_000_000));
|
|
46
|
+
/** A cap on guests' daily model cost, in US dollars: more than nothing, at most `ceiling`. */
|
|
47
|
+
function usdCap(ceiling) {
|
|
48
|
+
return Schema.Number.check(Schema.isFinite(), Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(ceiling));
|
|
49
|
+
}
|
|
45
50
|
/**
|
|
46
51
|
* The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
|
|
47
|
-
* `guest` limits guests' turns, apart from those of people who signed up
|
|
52
|
+
* `guest` limits guests' turns, apart from those of people who signed up, and, when the agent sets
|
|
53
|
+
* them, the model cost of each guest's turns and of every guest's together each day.
|
|
48
54
|
*/
|
|
49
55
|
export const AgentLimitsRequest = Schema.Struct({
|
|
50
56
|
perSender: Schema.optionalKey(Schema.Struct({
|
|
@@ -56,8 +62,42 @@ export const AgentLimitsRequest = Schema.Struct({
|
|
|
56
62
|
guest: Schema.optionalKey(Schema.Struct({
|
|
57
63
|
turnsPerDay: Schema.optionalKey(PositiveLimit),
|
|
58
64
|
workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
|
|
65
|
+
usdPerDay: Schema.optionalKey(usdCap(GUEST_USD_CEILINGS.usdPerDay)),
|
|
66
|
+
workspaceUsdPerDay: Schema.optionalKey(usdCap(GUEST_USD_CEILINGS.workspaceUsdPerDay)),
|
|
59
67
|
})),
|
|
60
68
|
});
|
|
69
|
+
/**
|
|
70
|
+
* `POST /api/ontology/agent/guests/usage` (runtime): the model cost of a guest's turn, as the
|
|
71
|
+
* runtime recorded it, for the guests' money caps. `key` names the report, so a retry adds nothing.
|
|
72
|
+
*/
|
|
73
|
+
export const GuestUsageRequest = Schema.Struct({
|
|
74
|
+
guest_id: Schema.String.check(Schema.isUUID()),
|
|
75
|
+
cost_usd: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(MAX_GUEST_USAGE_REPORT_USD)),
|
|
76
|
+
key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
|
|
77
|
+
});
|
|
78
|
+
/** An email address a guest gives, as the app's sign-in takes one. */
|
|
79
|
+
const GuestEmail = Schema.String.check(Schema.isMinLength(3), Schema.isMaxLength(320));
|
|
80
|
+
/**
|
|
81
|
+
* `POST /api/ontology/agent/guests/email-code`: the address a guest proves, and the page of the
|
|
82
|
+
* guest's website an emailed link returns to.
|
|
83
|
+
*/
|
|
84
|
+
export const GuestEmailCodeRequest = Schema.Struct({
|
|
85
|
+
email: GuestEmail,
|
|
86
|
+
return_to: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2048))),
|
|
87
|
+
});
|
|
88
|
+
/**
|
|
89
|
+
* `POST /api/ontology/agent/guests/sign-up`: the address and the code it received, or the handoff
|
|
90
|
+
* an opened link gave the guest's browser.
|
|
91
|
+
*/
|
|
92
|
+
export const GuestSignUpRequest = Schema.Union([
|
|
93
|
+
Schema.Struct({
|
|
94
|
+
email: GuestEmail,
|
|
95
|
+
code: Schema.String.check(Schema.isPattern(/^[0-9]{4,12}$/)),
|
|
96
|
+
}),
|
|
97
|
+
Schema.Struct({
|
|
98
|
+
handoff: Schema.String.check(Schema.isMinLength(16), Schema.isMaxLength(256)),
|
|
99
|
+
}),
|
|
100
|
+
]);
|
|
61
101
|
export const ResolveIdentityRequest = Schema.Struct({
|
|
62
102
|
...PairingRequest.fields,
|
|
63
103
|
chat: Schema.Literals(["private", "group"]),
|