@vercel/board 0.33.0 → 0.35.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/dist/{access-N3XmkKXg.mjs → access-BsP0hvcC.mjs} +169 -12
- package/dist/access.d.mts +3 -3
- package/dist/access.mjs +5 -5
- package/dist/{actors-ihyN47OV.mjs → actors-DFOpTw89.mjs} +2 -2
- package/dist/{auth-D6z3rMNj.d.mts → auth-C21V0EK1.d.mts} +128 -9
- package/dist/auth-CrjXLgOb.mjs +599 -0
- package/dist/{backend-CWpyR1A7.d.mts → backend-D21q8mdm.d.mts} +30 -7
- package/dist/backend-local.d.mts +1 -1
- package/dist/backend-local.mjs +1 -1
- package/dist/{chat-provider-DJpFUaFv.d.mts → chat-provider-DmZCmBkb.d.mts} +2 -2
- package/dist/cli-commands.d.mts +1 -1
- package/dist/cli-commands.mjs +1 -1
- package/dist/cli-embedded.d.mts +2 -2
- package/dist/cli-embedded.mjs +1 -1
- package/dist/cli.mjs +5 -5
- package/dist/{commands-BOBQHVqM.d.mts → commands-BorACIFS.d.mts} +168 -1
- package/dist/{commands-CHoMl06v.mjs → commands-CENWob9m.mjs} +281 -11
- package/dist/{conformance-qKmGLTAT.mjs → conformance-CKrwglzA.mjs} +491 -105
- package/dist/conformance.d.mts +20 -2
- package/dist/conformance.mjs +1 -1
- package/dist/{engine-JxgZiikU.mjs → engine-wN7quvbU.mjs} +2 -2
- package/dist/{errors-Pk0XV1hK.mjs → errors-rYDxZEuN.mjs} +116 -7
- package/dist/exports-BxljH73E.d.mts +4 -0
- package/dist/{exports-gHDHlg0i.mjs → exports-GIRJm2Ja.mjs} +136 -26
- package/dist/{index-CXvvYNYj.d.mts → index-LREsSZb2.d.mts} +2 -2
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +4 -4
- package/dist/index.node.d.mts +6 -6
- package/dist/index.node.mjs +3 -3
- package/dist/inspect/app.js +32 -32
- package/dist/{local-BbLjA5vI.mjs → local-yKwdgukb.mjs} +1981 -1574
- package/dist/{main-CQpCZJFw.mjs → main-DjokcEAL.mjs} +440 -50
- package/dist/{middleware-BU7rVi9F.mjs → middleware-BxgizazV.mjs} +1 -1
- package/dist/provider-DEOfc4Ls.d.mts +1049 -0
- package/dist/{provider-BlzUvcM9.d.mts → routes-BpKdMvgX.d.mts} +2461 -2480
- package/dist/{serve-D8_W4UN6.mjs → serve-CJ8hauK2.mjs} +4 -4
- package/dist/{server-BiIUXWbU.mjs → server-CtaTtyhw.mjs} +7 -7
- package/dist/{serving-D7rcUtSC.mjs → serving-6_bhBNAW.mjs} +1 -1
- package/dist/sync-chat-sdk.d.mts +2 -2
- package/dist/sync-github.d.mts +2 -2
- package/dist/sync-linear.d.mts +3 -2
- package/dist/sync-slack.d.mts +3 -3
- package/dist/sync.d.mts +2 -2
- package/dist/{targets-CknPGGVi.mjs → targets-n2i2ZOWI.mjs} +104 -12
- package/dist/{tokens-DPKjl3jf.mjs → tokens-Dn4cPZIr.mjs} +2 -2
- package/docs/01-board/01-mounting.md +12 -5
- package/docs/01-board/03-identity.md +14 -13
- package/docs/01-board/07-schedules.md +1 -1
- package/docs/01-board/09-access.md +170 -58
- package/docs/03-guides/03-ci.md +19 -17
- package/docs/03-guides/05-agent-factory.md +5 -6
- package/docs/04-reference/01-cli.md +99 -22
- package/docs/04-reference/02-board.md +42 -11
- package/docs/04-reference/03-http.md +21 -14
- package/docs/04-reference/05-conformance.md +31 -5
- package/package.json +1 -1
- package/dist/auth-r-_PeZyw.mjs +0 -277
- package/dist/exports-BuKjVq2t.d.mts +0 -4
- package/dist/folds-DjFTiqIM.d.mts +0 -552
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { a as forbidden$1, c as toErrorResponse, f as duration, g as fileName, h as IMPORT_BYTES_MAX, i as duplicateId, l as unauthorized, m as DIRECT_UPLOAD_BYTES_MAX, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-
|
|
1
|
+
import { a as forbidden$1, c as toErrorResponse, f as duration, g as fileName, h as IMPORT_BYTES_MAX, i as duplicateId, l as unauthorized, m as DIRECT_UPLOAD_BYTES_MAX, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-rYDxZEuN.mjs";
|
|
2
2
|
import { _ as actorKind, a as ChannelPath, c as LabelKey, f as MessageId, g as SeenActorKind, h as SCOPE_MAX, i as Author, m as RemoteWatcherId, n as Attachment, o as Emoji, p as MessageText, s as Handle, t as ActorId, u as Labels, v as platformAvatar, y as storable } from "./schemas-BG205xds.mjs";
|
|
3
3
|
import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-CYe424fO.mjs";
|
|
4
|
-
import { a as compileWatcher, c as METHODS, h as VERSION, i as canonicalWatchers, m as SYNC, n as syncTarget, o as hasCriteria, r as withEmailMentions } from "./targets-
|
|
5
|
-
import { i as waitUntil, n as MIDDLEWARE_ACTOR, o as derivedId, s as isKeyIdOf, t as DroppedError } from "./middleware-
|
|
6
|
-
import {
|
|
4
|
+
import { a as compileWatcher, c as METHODS, h as VERSION, i as canonicalWatchers, m as SYNC, n as syncTarget, o as hasCriteria, r as withEmailMentions } from "./targets-n2i2ZOWI.mjs";
|
|
5
|
+
import { i as waitUntil, n as MIDDLEWARE_ACTOR, o as derivedId, s as isKeyIdOf, t as DroppedError } from "./middleware-BxgizazV.mjs";
|
|
6
|
+
import { a as checkGrantChange, d as scopeOf, i as authorize, s as compileAccess, t as FULL_ACCESS, u as parseScope } from "./access-BsP0hvcC.mjs";
|
|
7
|
+
import { C as workflowPath, c as checkGrant, f as grantIssuers, h as joined, l as checkPrincipal, m as issuerName, n as DEFAULT_CAN, o as authenticates, r as GITHUB_ISSUER, s as checkCan, t as BOARD_TOKEN_PREFIX, v as removes, w as wroteAs, y as tokenHash } from "./auth-CrjXLgOb.mjs";
|
|
7
8
|
import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
|
|
8
9
|
import { n as replaceMentions } from "./mentions-CB6ShY4R.mjs";
|
|
9
|
-
import { a as resolveMentions, n as actorSeen } from "./actors-
|
|
10
|
-
import { h as tokenHash, n as DEFAULT_CAN, o as authenticates, s as checkGrant, t as BOARD_TOKEN_PREFIX, u as grantIssuers, v as wroteAs } from "./auth-r-_PeZyw.mjs";
|
|
10
|
+
import { a as resolveMentions, n as actorSeen } from "./actors-DFOpTw89.mjs";
|
|
11
11
|
import { C as sessionClearedError, a as SOCKET_TIMINGS, c as drainSettledHooks, d as nullProtoRecord, f as runtimeConsumerFactory, g as A2Error, h as stateTailReaders, i as RESERVED_PARTICIPANT_IDS, l as failedPreviousAttempt, m as serverInternals, n as POLL_TIMINGS, o as STATE_CACHE, p as runtimeConsumers, r as PRESENCE_TIMINGS, s as STREAM_TIMINGS, t as DRAIN_TIMINGS, u as markSchedulerSendFailure, v as NonRetriableError, x as isSessionCleared, y as asStoreUnavailable } from "./internal-CvsrprnU-CEPOUpAv.mjs";
|
|
12
12
|
import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
|
|
13
13
|
import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-BQzKUqQt.mjs";
|
|
@@ -4234,25 +4234,87 @@ const Grant = z.union([z.literal("all"), z.array(z.string().min(1).max(16)).max(
|
|
|
4234
4234
|
/** A `can`, as config writes it: board() checks it before it's kept. */
|
|
4235
4235
|
const Can = z.union([Grant, z.record(z.string().min(1).max(300), Grant)]);
|
|
4236
4236
|
const ClaimValue = z.string().min(1).max(1e3);
|
|
4237
|
+
const Environments = z.array(z.string().min(1).max(100)).max(16);
|
|
4238
|
+
/** Who a grant names, as the board keeps it: IDs, with the names it knows beside them. */
|
|
4239
|
+
const GrantPrincipal = z.discriminatedUnion("kind", [
|
|
4240
|
+
z.object({
|
|
4241
|
+
kind: z.literal("user"),
|
|
4242
|
+
userId: z.string().min(1).max(200),
|
|
4243
|
+
email: z.string().max(320).optional()
|
|
4244
|
+
}),
|
|
4245
|
+
z.object({
|
|
4246
|
+
kind: z.literal("project"),
|
|
4247
|
+
projectId: z.string().min(1).max(200),
|
|
4248
|
+
name: z.string().max(200).optional(),
|
|
4249
|
+
environments: Environments,
|
|
4250
|
+
teamId: z.string().min(1).max(200).optional()
|
|
4251
|
+
}),
|
|
4252
|
+
z.object({
|
|
4253
|
+
kind: z.literal("github"),
|
|
4254
|
+
repository: z.string().min(1).max(200),
|
|
4255
|
+
repositoryId: z.string().min(1).max(64).optional(),
|
|
4256
|
+
workflow: z.string().min(1).max(300).optional(),
|
|
4257
|
+
branch: z.string().min(1).max(255).optional(),
|
|
4258
|
+
event: z.string().min(1).max(64).optional()
|
|
4259
|
+
}),
|
|
4260
|
+
z.object({
|
|
4261
|
+
kind: z.literal("oidc"),
|
|
4262
|
+
issuer: z.string().min(1).max(1e3),
|
|
4263
|
+
claims: z.record(z.string().min(1).max(200), z.union([ClaimValue, z.array(ClaimValue).min(1).max(32)]))
|
|
4264
|
+
}),
|
|
4265
|
+
z.object({ kind: z.literal("all-users") }),
|
|
4266
|
+
z.object({
|
|
4267
|
+
kind: z.literal("all-projects"),
|
|
4268
|
+
environments: Environments
|
|
4269
|
+
}),
|
|
4270
|
+
z.object({
|
|
4271
|
+
kind: z.literal("app"),
|
|
4272
|
+
clientId: z.string().min(1).max(200),
|
|
4273
|
+
name: z.string().max(200).optional()
|
|
4274
|
+
}),
|
|
4275
|
+
z.object({ kind: z.literal("all-apps") }),
|
|
4276
|
+
z.object({ kind: z.literal("everyone") })
|
|
4277
|
+
]);
|
|
4278
|
+
/** A grant's `can`, as written: each pattern and `'all'` or its permissions. */
|
|
4279
|
+
const GrantCan = z.record(z.string().min(1).max(300), Grant);
|
|
4237
4280
|
/**
|
|
4238
4281
|
* Who the board trusts beside its code's rules, outside the board log: grants, and the tokens it
|
|
4239
|
-
* issued, of which only a hash is kept. Session `access`. A
|
|
4240
|
-
*
|
|
4282
|
+
* issued, of which only a hash is kept. Session `access`. A token's ID is the index of the event
|
|
4283
|
+
* that made it; a grant's comes from the fold, counting from the one the board starts with.
|
|
4241
4284
|
*/
|
|
4242
4285
|
const accessContract = contract({
|
|
4243
4286
|
name: "board-access",
|
|
4244
4287
|
events: {
|
|
4245
|
-
/**
|
|
4288
|
+
/** From before grants named principals: kept so older logs load, and folded into nothing. */
|
|
4246
4289
|
"grant.set": z.object({
|
|
4247
4290
|
issuer: z.string().min(1).max(1e3),
|
|
4248
4291
|
claims: z.record(z.string().min(1).max(200), z.union([ClaimValue, z.array(ClaimValue).min(1).max(32)])),
|
|
4249
4292
|
can: Can,
|
|
4250
4293
|
by: ActorId
|
|
4251
4294
|
}),
|
|
4295
|
+
/** From before grants named principals: folded into nothing, so it can't take a grant made since. */
|
|
4252
4296
|
"grant.revoked": z.object({
|
|
4253
4297
|
id: z.number().int().positive(),
|
|
4254
4298
|
by: ActorId
|
|
4255
4299
|
}),
|
|
4300
|
+
/** A new grant: who it names, and what it lets them do. */
|
|
4301
|
+
"grant.created": z.object({
|
|
4302
|
+
principals: z.array(GrantPrincipal).min(1).max(32),
|
|
4303
|
+
can: GrantCan,
|
|
4304
|
+
by: ActorId
|
|
4305
|
+
}),
|
|
4306
|
+
/** A grant as it is now, after an update. */
|
|
4307
|
+
"grant.updated": z.object({
|
|
4308
|
+
id: z.number().int().positive(),
|
|
4309
|
+
principals: z.array(GrantPrincipal).min(1).max(32),
|
|
4310
|
+
can: GrantCan,
|
|
4311
|
+
by: ActorId
|
|
4312
|
+
}),
|
|
4313
|
+
/** A grant revoked. */
|
|
4314
|
+
"grant.deleted": z.object({
|
|
4315
|
+
id: z.number().int().positive(),
|
|
4316
|
+
by: ActorId
|
|
4317
|
+
}),
|
|
4256
4318
|
"token.minted": z.object({
|
|
4257
4319
|
/** The secret's SHA-256, hex. */
|
|
4258
4320
|
hash: z.string().regex(/^[0-9a-f]{64}$/),
|
|
@@ -4277,1701 +4339,2042 @@ const accessContract = contract({
|
|
|
4277
4339
|
}
|
|
4278
4340
|
});
|
|
4279
4341
|
const ACCESS_SESSION = "access";
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
const DAY_MS = 864e5;
|
|
4287
|
-
/** What makes two grants one: the issuer, and the claims with their names sorted. */
|
|
4288
|
-
const grantKey = (issuer, claims) => JSON.stringify([issuer, Object.keys(claims).sort().map((name) => [name, claims[name]])]);
|
|
4289
|
-
function dropToken(state, id) {
|
|
4290
|
-
const row = state.tokens[id];
|
|
4291
|
-
if (!row) return;
|
|
4292
|
-
delete state.hashes[row.hash];
|
|
4293
|
-
delete state.tokens[id];
|
|
4294
|
-
}
|
|
4295
|
-
/** Whether token `id` is token `ancestor`, or was minted with it at any depth. */
|
|
4296
|
-
function mintedWith(state, id, ancestor) {
|
|
4297
|
-
let at = id;
|
|
4298
|
-
for (let depth = 0; at !== null && depth <= TOKEN_DEPTH_MAX; depth++) {
|
|
4299
|
-
if (at === ancestor) return true;
|
|
4300
|
-
at = state.tokens[at]?.parent ?? null;
|
|
4301
|
-
}
|
|
4302
|
-
return false;
|
|
4303
|
-
}
|
|
4304
|
-
/**
|
|
4305
|
-
* Whether `identity` may see and revoke token `row`: anyone's with `manage` in every channel. A
|
|
4306
|
-
* token acts as its minter, so its principal alone would hand it every token its minter has: with
|
|
4307
|
-
* a token, it's that token and those minted with it; without one, those its principal minted.
|
|
4308
|
-
*/
|
|
4309
|
-
function manages(state, { principal }, row) {
|
|
4310
|
-
if (principal.access.everywhere("manage")) return true;
|
|
4311
|
-
if (row.minter.id !== principal.id) return false;
|
|
4312
|
-
if (principal.token === void 0) return true;
|
|
4313
|
-
const held = indexOf$1(principal.token, "t");
|
|
4314
|
-
return held !== null && mintedWith(state, row.id, held);
|
|
4315
|
-
}
|
|
4316
|
-
/**
|
|
4317
|
-
* The access session's fold. It prunes by the events' own times, so every instance folds the same
|
|
4318
|
-
* state, and each event costs a day's expired tokens at most. A child whose parent is gone counts
|
|
4319
|
-
* as dead (`liveIn`), and lives no longer than its parent, so pruning never brings one back.
|
|
4320
|
-
*/
|
|
4321
|
-
function foldAccess(state, event) {
|
|
4322
|
-
const at = new Date(event.createdAt).getTime();
|
|
4323
|
-
const day = Math.floor(at / DAY_MS);
|
|
4324
|
-
if (state.pruned === null) state.pruned = day;
|
|
4325
|
-
for (; state.pruned < day; state.pruned++) {
|
|
4326
|
-
for (const id of state.expiring[state.pruned] ?? []) dropToken(state, id);
|
|
4327
|
-
delete state.expiring[state.pruned];
|
|
4342
|
+
reducer({
|
|
4343
|
+
contract: boardContract,
|
|
4344
|
+
name: "board.messages.v5",
|
|
4345
|
+
initialState: {
|
|
4346
|
+
byId: {},
|
|
4347
|
+
replies: {}
|
|
4328
4348
|
}
|
|
4329
|
-
|
|
4330
|
-
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
case "grant.revoked": {
|
|
4353
|
-
const key = state.grantKeys[event.payload.id];
|
|
4354
|
-
if (key !== void 0) {
|
|
4355
|
-
delete state.grants[key];
|
|
4356
|
-
delete state.grantKeys[event.payload.id];
|
|
4357
|
-
}
|
|
4358
|
-
break;
|
|
4359
|
-
}
|
|
4360
|
-
case "token.minted": {
|
|
4361
|
-
const { payload } = event;
|
|
4362
|
-
if (state.hashes[payload.hash] !== void 0) break;
|
|
4363
|
-
state.tokens[event.index] = {
|
|
4364
|
-
id: event.index,
|
|
4365
|
-
...payload,
|
|
4366
|
-
minter: payload.minter,
|
|
4367
|
-
at
|
|
4368
|
-
};
|
|
4369
|
-
state.hashes[payload.hash] = event.index;
|
|
4370
|
-
(state.expiring[Math.floor(payload.expiresAt / DAY_MS)] ??= []).push(event.index);
|
|
4371
|
-
break;
|
|
4372
|
-
}
|
|
4373
|
-
case "token.revoked": dropToken(state, event.payload.id);
|
|
4349
|
+
}).fold(foldMessages);
|
|
4350
|
+
reducer({
|
|
4351
|
+
contract: boardContract,
|
|
4352
|
+
name: "board.posted.v1",
|
|
4353
|
+
initialState: {}
|
|
4354
|
+
}).fold((state, event) => {
|
|
4355
|
+
if (event.type === "message.posted") setOwn(state, event.id, event.index);
|
|
4356
|
+
return state;
|
|
4357
|
+
});
|
|
4358
|
+
const emptyChannel = (path) => ({
|
|
4359
|
+
path,
|
|
4360
|
+
lastIndex: 0,
|
|
4361
|
+
messages: 0,
|
|
4362
|
+
threads: 0
|
|
4363
|
+
});
|
|
4364
|
+
const channelsReducer = reducer({
|
|
4365
|
+
contract: boardContract,
|
|
4366
|
+
name: "board.channels.v2",
|
|
4367
|
+
initialState: {}
|
|
4368
|
+
}).fold((state, event) => {
|
|
4369
|
+
if (event.type === "channel.created") {
|
|
4370
|
+
if (!own(state, event.payload.channel)) setOwn(state, event.payload.channel, emptyChannel(event.payload.channel));
|
|
4371
|
+
return state;
|
|
4374
4372
|
}
|
|
4373
|
+
if (event.type !== "message.posted") return state;
|
|
4374
|
+
const { channel, re } = event.payload;
|
|
4375
|
+
const entry = own(state, channel) ?? setOwn(state, channel, emptyChannel(channel));
|
|
4376
|
+
entry.lastIndex = event.index;
|
|
4377
|
+
entry.messages += 1;
|
|
4378
|
+
if (re === null) entry.threads += 1;
|
|
4375
4379
|
return state;
|
|
4376
|
-
}
|
|
4377
|
-
const
|
|
4378
|
-
contract:
|
|
4379
|
-
name: "board.
|
|
4380
|
+
});
|
|
4381
|
+
const actorsReducer = reducer({
|
|
4382
|
+
contract: boardContract,
|
|
4383
|
+
name: "board.actors.v2",
|
|
4380
4384
|
initialState: {
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
tokens: {},
|
|
4384
|
-
hashes: {},
|
|
4385
|
-
expiring: {},
|
|
4386
|
-
pruned: null
|
|
4385
|
+
byId: {},
|
|
4386
|
+
byHandle: {}
|
|
4387
4387
|
}
|
|
4388
|
-
}).fold(
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
/**
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4388
|
+
}).fold(foldActors);
|
|
4389
|
+
//#endregion
|
|
4390
|
+
//#region src/server/feed.ts
|
|
4391
|
+
/** Bookkeeping events, shown only with `all`: who's who, and delivery receipts. */
|
|
4392
|
+
const HIDDEN = /* @__PURE__ */ new Set([
|
|
4393
|
+
"actor.seen",
|
|
4394
|
+
"message.synced",
|
|
4395
|
+
"message.files_synced"
|
|
4396
|
+
]);
|
|
4397
|
+
function actorView(actors, id) {
|
|
4398
|
+
const author = own(actors.byId, id);
|
|
4399
|
+
if (!author) return null;
|
|
4400
|
+
return {
|
|
4401
|
+
kind: author.kind,
|
|
4402
|
+
handle: author.handle,
|
|
4403
|
+
name: author.name,
|
|
4404
|
+
avatar: author.avatar
|
|
4405
|
+
};
|
|
4395
4406
|
}
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
|
|
4413
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
4417
|
-
|
|
4418
|
-
|
|
4419
|
-
|
|
4407
|
+
/** The board's own code, which reads every channel: it needs no messages to say so. */
|
|
4408
|
+
const OWN_CODE = {
|
|
4409
|
+
access: FULL_ACCESS,
|
|
4410
|
+
channelOf: () => void 0
|
|
4411
|
+
};
|
|
4412
|
+
/** The board messages `links` point to, for `Reader.channelOf`. */
|
|
4413
|
+
const linkedIds = (links) => links.flatMap((link) => link.message === null ? [] : [link.message]);
|
|
4414
|
+
/**
|
|
4415
|
+
* Links as `reader` may see them. The log keeps each snapshot; it's hidden when
|
|
4416
|
+
* it's read. A linked message the reader's lookup doesn't have hides too: its
|
|
4417
|
+
* snapshot shows only where it's known to be readable.
|
|
4418
|
+
*/
|
|
4419
|
+
function readableLinks(links, reader) {
|
|
4420
|
+
return links.map((link) => {
|
|
4421
|
+
if (link.message === null) return {
|
|
4422
|
+
...link,
|
|
4423
|
+
message: null
|
|
4424
|
+
};
|
|
4425
|
+
const channel = reader.access.readsAll ? void 0 : reader.channelOf(link.message);
|
|
4426
|
+
return reader.access.readsAll || channel !== void 0 && reader.access.readable(channel) ? {
|
|
4427
|
+
...link,
|
|
4428
|
+
message: ref(link.message)
|
|
4429
|
+
} : {
|
|
4430
|
+
url: link.url,
|
|
4431
|
+
message: null,
|
|
4432
|
+
snapshot: null,
|
|
4433
|
+
unavailable: "not_readable"
|
|
4434
|
+
};
|
|
4435
|
+
});
|
|
4420
4436
|
}
|
|
4421
|
-
|
|
4422
|
-
|
|
4437
|
+
/** The links in an event view: its payload's, its message's, and the message before a label change. */
|
|
4438
|
+
const viewLinks = (view) => {
|
|
4439
|
+
const { payload, message, before } = view;
|
|
4440
|
+
return [
|
|
4441
|
+
payload?.links,
|
|
4442
|
+
message?.links,
|
|
4443
|
+
before?.links
|
|
4444
|
+
].filter((links) => links !== void 0);
|
|
4423
4445
|
};
|
|
4446
|
+
/** The board messages an event view's links point to, for a reader of them. */
|
|
4447
|
+
const viewLinkedIds = (view) => viewLinks(view).flatMap((links) => links.flatMap((link) => link.message === null ? [] : [indexOf$1(link.message) ?? 0]));
|
|
4424
4448
|
/**
|
|
4425
|
-
*
|
|
4426
|
-
*
|
|
4427
|
-
*
|
|
4449
|
+
* An event view made for one reader, as `reader` sees it: a link to a message it can't read shows
|
|
4450
|
+
* nothing of it. A watcher's match is made when its event lands and pulled later, by whatever its
|
|
4451
|
+
* registrant may read then.
|
|
4428
4452
|
*/
|
|
4429
|
-
function
|
|
4430
|
-
|
|
4431
|
-
|
|
4432
|
-
|
|
4433
|
-
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
}
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
4453
|
-
|
|
4454
|
-
|
|
4455
|
-
|
|
4456
|
-
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
4461
|
-
|
|
4462
|
-
|
|
4463
|
-
|
|
4464
|
-
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
|
|
4471
|
-
|
|
4472
|
-
|
|
4473
|
-
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
4490
|
-
|
|
4491
|
-
|
|
4492
|
-
|
|
4493
|
-
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
};
|
|
4516
|
-
},
|
|
4517
|
-
async revokeGrant(identity, { id }) {
|
|
4518
|
-
needsManage(identity, "revoke grants");
|
|
4519
|
-
const index = indexOf$1(id, "g");
|
|
4520
|
-
if (index === null || (await read()).grantKeys[index] === void 0) return { revoked: false };
|
|
4521
|
-
await session.append({
|
|
4522
|
-
type: "grant.revoked",
|
|
4523
|
-
payload: {
|
|
4524
|
-
id: index,
|
|
4525
|
-
by: identity.actor.id
|
|
4526
|
-
}
|
|
4527
|
-
});
|
|
4528
|
-
return { revoked: true };
|
|
4529
|
-
},
|
|
4530
|
-
async tokens(identity) {
|
|
4531
|
-
const state = await read();
|
|
4532
|
-
return { tokens: await viewsOf(Object.values(state.tokens).filter((row) => liveIn(state, row.id) && manages(state, identity, row)).sort((a, b) => a.id - b.id)) };
|
|
4533
|
-
},
|
|
4534
|
-
/** The board tokens `principal` came with: its own, then each it was minted with. Undefined with none. */
|
|
4535
|
-
async chain(principal) {
|
|
4536
|
-
if (principal.token === void 0) return void 0;
|
|
4537
|
-
const state = await read();
|
|
4538
|
-
const chain = [];
|
|
4539
|
-
for (let at = indexOf$1(principal.token, "t"); at !== null && chain.length <= TOKEN_DEPTH_MAX; at = state.tokens[at]?.parent ?? null) chain.push(tokenId(at));
|
|
4540
|
-
return chain;
|
|
4541
|
-
},
|
|
4542
|
-
async createToken(identity, body) {
|
|
4543
|
-
const { principal, author, actor } = identity;
|
|
4544
|
-
const state = await read();
|
|
4545
|
-
const now = Date.now();
|
|
4546
|
-
const asked = body.expires === void 0 ? TOKEN_DEFAULT_MS : duration(body.expires);
|
|
4547
|
-
if (asked <= 0 || asked > 7776e6) throw badRequest("a token lives up to 90 days: pass expires as 90d or less", "invalid_expires");
|
|
4548
|
-
let expiresAt = now + asked;
|
|
4549
|
-
let parent = null;
|
|
4550
|
-
if (principal.token !== void 0) {
|
|
4551
|
-
const index = indexOf$1(principal.token, "t");
|
|
4552
|
-
parent = index === null ? null : state.tokens[index] ?? null;
|
|
4553
|
-
if (!parent || !liveIn(state, parent.id)) throw unauthorized("invalid token: revoked, expired, or not this board's");
|
|
4554
|
-
let depth = 0;
|
|
4555
|
-
for (let at = parent; at; at = at.parent === null ? void 0 : state.tokens[at.parent]) depth++;
|
|
4556
|
-
if (depth >= TOKEN_DEPTH_MAX) throw badRequest(`tokens minted with tokens go ${TOKEN_DEPTH_MAX} deep at most`, "invalid_token");
|
|
4557
|
-
expiresAt = Math.min(expiresAt, parent.expiresAt);
|
|
4558
|
-
}
|
|
4559
|
-
let can;
|
|
4560
|
-
try {
|
|
4561
|
-
can = compileAccess(body.can ?? DEFAULT_CAN);
|
|
4562
|
-
} catch (error) {
|
|
4563
|
-
throw badRequest(error.message, "invalid_scope");
|
|
4564
|
-
}
|
|
4565
|
-
const scope = scopeOf((principal.scope === void 0 ? FULL_ACCESS : compileAccess(parseScope(principal.scope))).narrow(can));
|
|
4566
|
-
if (scope.length > 4e3) throw badRequest(`a token's can is ${SCOPE_MAX} characters at most as a scope: name fewer channels`, "invalid_scope");
|
|
4567
|
-
const minter = {
|
|
4568
|
-
id: principal.id,
|
|
4569
|
-
kind: principal.kind,
|
|
4570
|
-
handle: principal.handle,
|
|
4571
|
-
...principal.facts ? { facts: principal.facts } : {},
|
|
4572
|
-
scope
|
|
4573
|
-
};
|
|
4574
|
-
const pinned = principal.pinned;
|
|
4575
|
-
const profile = pinned?.profile ?? body.profile ?? null;
|
|
4576
|
-
const avatar = pinned?.profile ? pinned.avatar : profile !== null ? body.avatar ?? null : null;
|
|
4577
|
-
const pinnedSession = pinned?.session ?? body.session ?? null;
|
|
4578
|
-
const person = principal.kind === "person";
|
|
4579
|
-
const base = author.profile === null ? actor.handle : actor.handle.slice(0, Math.max(0, actor.handle.length - author.profile.length - 1)) || principal.handle;
|
|
4580
|
-
const handle = pinned?.handle ?? (person ? base : null);
|
|
4581
|
-
const personName = pinned?.name ?? (person && author.profile === null ? actor.name : null);
|
|
4582
|
-
const secret = newSecret();
|
|
4583
|
-
const [row] = await session.append({
|
|
4584
|
-
type: "token.minted",
|
|
4585
|
-
payload: {
|
|
4586
|
-
hash: await tokenHash(secret),
|
|
4587
|
-
name: body.name,
|
|
4588
|
-
minter,
|
|
4589
|
-
profile,
|
|
4590
|
-
avatar,
|
|
4591
|
-
session: pinnedSession,
|
|
4592
|
-
handle,
|
|
4593
|
-
personName,
|
|
4594
|
-
expiresAt,
|
|
4595
|
-
parent: parent?.id ?? null,
|
|
4596
|
-
by: actor.id
|
|
4597
|
-
}
|
|
4598
|
-
});
|
|
4599
|
-
const minted = row && (await read()).tokens[row.index];
|
|
4600
|
-
if (!minted) throw new Error("a token was minted but its log has no record of it");
|
|
4601
|
-
const [view] = await viewsOf([minted]);
|
|
4602
|
-
return {
|
|
4603
|
-
token: view,
|
|
4604
|
-
secret
|
|
4605
|
-
};
|
|
4606
|
-
},
|
|
4607
|
-
async revokeToken(identity, { id }) {
|
|
4608
|
-
const state = await read();
|
|
4609
|
-
const index = indexOf$1(id, "t");
|
|
4610
|
-
const row = index === null ? void 0 : state.tokens[index];
|
|
4611
|
-
if (!row || !liveIn(state, row.id) || !manages(state, identity, row)) return { revoked: false };
|
|
4612
|
-
await session.append({
|
|
4613
|
-
type: "token.revoked",
|
|
4614
|
-
payload: {
|
|
4615
|
-
id: row.id,
|
|
4616
|
-
by: identity.actor.id
|
|
4617
|
-
}
|
|
4618
|
-
});
|
|
4619
|
-
return { revoked: true };
|
|
4453
|
+
function viewedBy(view, reader) {
|
|
4454
|
+
if (reader.access.readsAll) return view;
|
|
4455
|
+
const shown = structuredClone(view);
|
|
4456
|
+
const reread = (links) => readableLinks(links.map((link) => ({
|
|
4457
|
+
...link,
|
|
4458
|
+
message: link.message === null ? null : indexOf$1(link.message) ?? 0
|
|
4459
|
+
})), reader);
|
|
4460
|
+
if (shown.payload?.links) shown.payload.links = reread(shown.payload.links);
|
|
4461
|
+
if (shown.message) shown.message.links = reread(shown.message.links);
|
|
4462
|
+
if (shown.before) shown.before.links = reread(shown.before.links);
|
|
4463
|
+
return shown;
|
|
4464
|
+
}
|
|
4465
|
+
/** A message's or a cursor's ID as clients see it. On this board it's the log index, in decimal. */
|
|
4466
|
+
const ref = (index) => String(index);
|
|
4467
|
+
/** A schedule's ID as clients see it: its index in session `schedules`, as `s12`, so it reads apart from message `12`. */
|
|
4468
|
+
const scheduleRef = (index) => `s${index}`;
|
|
4469
|
+
/** The log index a ref names on this board, or null for a string that names nothing here. */
|
|
4470
|
+
const indexOf$1 = (value) => /^(0|[1-9]\d{0,15})$/.test(value) ? Number(value) : null;
|
|
4471
|
+
/** A message as `reader` sees it. Every view names its reader, so none shows a link's snapshot by default. */
|
|
4472
|
+
function view(message, actors, reader) {
|
|
4473
|
+
const { blind, version, revision, schedule, ...shown } = message;
|
|
4474
|
+
return {
|
|
4475
|
+
...shown,
|
|
4476
|
+
...blind ? { blind } : {},
|
|
4477
|
+
id: ref(message.id),
|
|
4478
|
+
re: message.re === null ? null : ref(message.re),
|
|
4479
|
+
replyTo: message.replyTo === null ? null : ref(message.replyTo),
|
|
4480
|
+
version: version ?? message.id,
|
|
4481
|
+
revision: revision ?? message.id,
|
|
4482
|
+
...schedule ? { schedule: {
|
|
4483
|
+
id: scheduleRef(schedule.id),
|
|
4484
|
+
n: schedule.n
|
|
4485
|
+
} } : {},
|
|
4486
|
+
links: readableLinks(message.links, reader),
|
|
4487
|
+
labels: { ...message.labels },
|
|
4488
|
+
reactions: Object.fromEntries(Object.entries(message.reactions).map(([emoji, ids]) => [emoji, [...ids]])),
|
|
4489
|
+
author: actorView(actors, message.by.actor)
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
4492
|
+
const actorSet = (value, actors) => own(actors.byId, value) ? /* @__PURE__ */ new Set([value]) : new Set(own(actors.byHandle, value.toLowerCase()) ?? []);
|
|
4493
|
+
/**
|
|
4494
|
+
* Who a `--by` or `--mentions` value covers. A person (`julian`) is everyone they
|
|
4495
|
+
* are: their own actor, and their agents (`julian/claude`). An agent or a platform
|
|
4496
|
+
* actor is just itself.
|
|
4497
|
+
*/
|
|
4498
|
+
function whoIs(value, actors) {
|
|
4499
|
+
const ids = actorSet(value, actors);
|
|
4500
|
+
return {
|
|
4501
|
+
actors: ids,
|
|
4502
|
+
principals: new Set([...ids].filter((id) => own(actors.byId, id)?.kind === "person"))
|
|
4503
|
+
};
|
|
4504
|
+
}
|
|
4505
|
+
/** Whether `author` is one of `who`: its actor, or an agent of one of its people. */
|
|
4506
|
+
const covers = (who, actor, principal) => who.actors.has(actor) || principal !== void 0 && who.principals.has(principal);
|
|
4507
|
+
const hasLabel = (labels, [key, values]) => Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
|
|
4508
|
+
/**
|
|
4509
|
+
* Compiles filters once; handles resolve against the actors known at that
|
|
4510
|
+
* moment. A label matches on the message or its thread's root, where sync puts
|
|
4511
|
+
* labels, so `pr=…` means the PR's whole conversation. `messages` is the live
|
|
4512
|
+
* state for that lookup. A message in a channel `access` can't read never
|
|
4513
|
+
* matches, whatever the filters say.
|
|
4514
|
+
*/
|
|
4515
|
+
function compileFilter(filters, context) {
|
|
4516
|
+
const { access } = context;
|
|
4517
|
+
const text = filters.text?.toLowerCase();
|
|
4518
|
+
const labels = filters.label ?? [];
|
|
4519
|
+
const channel = filters.channel;
|
|
4520
|
+
const subtree = channel?.endsWith("/") ? channel.slice(0, -1) : null;
|
|
4521
|
+
const by = filters.by === void 0 ? null : whoIs(filters.by, context.actors);
|
|
4522
|
+
const re = filters.re === void 0 ? void 0 : indexOf$1(filters.re) ?? -1;
|
|
4523
|
+
const mentions = filters.mentions === void 0 ? null : filters.mentions === "me" ? new Set(context.me === null ? [] : [context.me]) : whoIs(filters.mentions, context.actors).actors;
|
|
4524
|
+
return (message) => {
|
|
4525
|
+
if (!message || !access.readable(message.channel)) return false;
|
|
4526
|
+
if (channel !== void 0) {
|
|
4527
|
+
if (subtree !== null) {
|
|
4528
|
+
if (message.channel !== subtree && !message.channel.startsWith(`${subtree}/`)) return false;
|
|
4529
|
+
} else if (message.channel !== channel) return false;
|
|
4530
|
+
}
|
|
4531
|
+
if (re !== void 0 && message.id !== re && message.re !== re) return false;
|
|
4532
|
+
if (by !== null && !covers(by, message.by.actor, message.by.principal)) return false;
|
|
4533
|
+
if (mentions !== null && !message.mentions.some((id) => mentions.has(id))) return false;
|
|
4534
|
+
if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
|
|
4535
|
+
if (text !== void 0 && !message.text.toLowerCase().includes(text)) return false;
|
|
4536
|
+
if (labels.length > 0) {
|
|
4537
|
+
const root = message.re === null ? void 0 : context.messages?.byId[message.re];
|
|
4538
|
+
for (const label of labels) if (!hasLabel(message.labels, label) && !(root && hasLabel(root.labels, label))) return false;
|
|
4620
4539
|
}
|
|
4540
|
+
return true;
|
|
4621
4541
|
};
|
|
4622
4542
|
}
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4543
|
+
/**
|
|
4544
|
+
* `filter`, narrowed to the channels `access` reads among `known`, as the tables
|
|
4545
|
+
* take it: a reader of every channel needs nothing more. A channel the caller
|
|
4546
|
+
* didn't know of is left out, never let in.
|
|
4547
|
+
*/
|
|
4548
|
+
function readableFilter(filter, known, access) {
|
|
4549
|
+
if (access.readsAll) return filter;
|
|
4550
|
+
const { channel, ...rest } = filter;
|
|
4551
|
+
const within = (path) => !channel || path === channel.path || channel.subtree && path.startsWith(`${channel.path}/`);
|
|
4552
|
+
return {
|
|
4553
|
+
...rest,
|
|
4554
|
+
channels: [...known].filter((path) => within(path) && access.readable(path))
|
|
4555
|
+
};
|
|
4556
|
+
}
|
|
4557
|
+
/** The filters as the tables take them: handles resolved to who they cover, `me` to the caller. */
|
|
4558
|
+
function toMessageFilter(filters, context) {
|
|
4559
|
+
const out = {};
|
|
4560
|
+
const channel = filters.channel;
|
|
4561
|
+
if (channel !== void 0) out.channel = channel.endsWith("/") ? {
|
|
4562
|
+
path: channel.slice(0, -1),
|
|
4563
|
+
subtree: true
|
|
4564
|
+
} : {
|
|
4565
|
+
path: channel,
|
|
4566
|
+
subtree: false
|
|
4567
|
+
};
|
|
4568
|
+
if (filters.re !== void 0) out.re = indexOf$1(filters.re) ?? -1;
|
|
4569
|
+
if (filters.by !== void 0) {
|
|
4570
|
+
const who = whoIs(filters.by, context.actors);
|
|
4571
|
+
out.by = {
|
|
4572
|
+
actors: [...who.actors],
|
|
4573
|
+
principals: [...who.principals]
|
|
4574
|
+
};
|
|
4575
|
+
}
|
|
4576
|
+
if (filters.mentions !== void 0) out.mentions = filters.mentions === "me" ? context.me === null ? [] : [context.me] : [...whoIs(filters.mentions, context.actors).actors];
|
|
4577
|
+
if (filters.from !== void 0) out.from = filters.from;
|
|
4578
|
+
if (filters.text !== void 0) out.text = filters.text.toLowerCase();
|
|
4579
|
+
if (filters.label?.length) out.labels = filters.label.map(([key, values]) => ({
|
|
4580
|
+
key,
|
|
4581
|
+
values
|
|
4582
|
+
}));
|
|
4583
|
+
return out;
|
|
4584
|
+
}
|
|
4585
|
+
/**
|
|
4586
|
+
* Loads into `messages`, as they were just before `event`, the message it
|
|
4587
|
+
* concerns and that message's root: what folding it and matching filters need.
|
|
4588
|
+
* `loaded` remembers what was asked for already, found or not.
|
|
4589
|
+
*/
|
|
4590
|
+
async function loadInto(reads, messages, loaded, event, signal) {
|
|
4591
|
+
const id = concernedMessageId(event);
|
|
4592
|
+
if (id === null) return;
|
|
4593
|
+
const through = event.index - 1;
|
|
4594
|
+
const load = async (ids) => {
|
|
4595
|
+
const wanted = ids.filter((want) => !loaded.has(want));
|
|
4596
|
+
if (wanted.length === 0) return;
|
|
4597
|
+
const found = await reads.messagesAt(wanted, through, signal);
|
|
4598
|
+
for (const want of wanted) {
|
|
4599
|
+
loaded.add(want);
|
|
4600
|
+
const message = found.get(want);
|
|
4601
|
+
if (message) messages.byId[want] = message;
|
|
4602
|
+
}
|
|
4603
|
+
};
|
|
4604
|
+
if (event.type === "message.posted") loaded.add(id);
|
|
4605
|
+
else await load([id]);
|
|
4606
|
+
const re = event.type === "message.posted" ? event.payload.re : messages.byId[id]?.re ?? null;
|
|
4607
|
+
if (re !== null) await load([re]);
|
|
4608
|
+
}
|
|
4609
|
+
/** The message `event` concerns and its root, as they were just before it. */
|
|
4610
|
+
async function loadBefore(reads, event, signal) {
|
|
4611
|
+
const messages = {
|
|
4627
4612
|
byId: {},
|
|
4628
4613
|
replies: {}
|
|
4614
|
+
};
|
|
4615
|
+
await loadInto(reads, messages, /* @__PURE__ */ new Set(), event, signal);
|
|
4616
|
+
return messages;
|
|
4617
|
+
}
|
|
4618
|
+
/** Folds one event into `messages` and `actors`, and returns the message it concerns before and after. */
|
|
4619
|
+
function foldEvent(messages, actors, event) {
|
|
4620
|
+
const id = concernedMessageId(event);
|
|
4621
|
+
const before = id === null ? void 0 : structuredClone(messages.byId[id]);
|
|
4622
|
+
foldMessages(messages, event);
|
|
4623
|
+
foldActors(actors, event);
|
|
4624
|
+
return {
|
|
4625
|
+
id,
|
|
4626
|
+
before,
|
|
4627
|
+
after: id === null ? void 0 : messages.byId[id]
|
|
4628
|
+
};
|
|
4629
|
+
}
|
|
4630
|
+
/** An event as subscribers receive it, with its message as it is afterwards. */
|
|
4631
|
+
function eventView(event, after, actors, reader) {
|
|
4632
|
+
const by = event.payload.by?.actor;
|
|
4633
|
+
const actor = by ? own(actors.byId, by) : void 0;
|
|
4634
|
+
const { links } = event.payload;
|
|
4635
|
+
return {
|
|
4636
|
+
cursor: ref(event.index),
|
|
4637
|
+
type: event.type,
|
|
4638
|
+
createdAt: iso(event.createdAt),
|
|
4639
|
+
payload: payloadView(event.payload, links ? readableLinks(links, reader) : void 0),
|
|
4640
|
+
...after ? { message: view(after, actors, reader) } : {},
|
|
4641
|
+
...actor ? { actor: {
|
|
4642
|
+
id: actor.id,
|
|
4643
|
+
...actorView(actors, actor.id)
|
|
4644
|
+
} } : {}
|
|
4645
|
+
};
|
|
4646
|
+
}
|
|
4647
|
+
/** An event's payload as clients see it: the message IDs in it are refs. */
|
|
4648
|
+
function payloadView(payload, links) {
|
|
4649
|
+
const shown = { ...payload };
|
|
4650
|
+
for (const key of [
|
|
4651
|
+
"id",
|
|
4652
|
+
"re",
|
|
4653
|
+
"replyTo"
|
|
4654
|
+
]) if (typeof shown[key] === "number") shown[key] = ref(shown[key]);
|
|
4655
|
+
const schedule = shown.schedule;
|
|
4656
|
+
if (schedule) shown.schedule = {
|
|
4657
|
+
id: scheduleRef(schedule.id),
|
|
4658
|
+
n: schedule.n
|
|
4659
|
+
};
|
|
4660
|
+
if (links) shown.links = links;
|
|
4661
|
+
return shown;
|
|
4662
|
+
}
|
|
4663
|
+
/**
|
|
4664
|
+
* Folds events one at a time and decides what a subscriber sees. It holds only
|
|
4665
|
+
* the messages events have touched, each loaded from the tables as it was just
|
|
4666
|
+
* before the first event that touched it. A label or reaction change is
|
|
4667
|
+
* delivered when its message matched the filter before *or* after it, so
|
|
4668
|
+
* subscribers see messages leave a view too.
|
|
4669
|
+
*
|
|
4670
|
+
* It's the one choke point for `/events` (tail, wait, and poll): an event about
|
|
4671
|
+
* a message shows only where `access` reads its channel, and one about no
|
|
4672
|
+
* message (who's who, a thread's sync) only to a reader of every channel.
|
|
4673
|
+
*/
|
|
4674
|
+
var FeedProjection = class {
|
|
4675
|
+
messages = {
|
|
4676
|
+
byId: {},
|
|
4677
|
+
replies: {}
|
|
4678
|
+
};
|
|
4679
|
+
loaded = /* @__PURE__ */ new Set();
|
|
4680
|
+
reads;
|
|
4681
|
+
actors;
|
|
4682
|
+
match;
|
|
4683
|
+
criteria;
|
|
4684
|
+
all;
|
|
4685
|
+
access;
|
|
4686
|
+
/** Where each board message a view links to lives, for a reader that can't read every channel. */
|
|
4687
|
+
linked = /* @__PURE__ */ new Map();
|
|
4688
|
+
constructor(options) {
|
|
4689
|
+
this.reads = options.reads;
|
|
4690
|
+
this.actors = options.actors;
|
|
4691
|
+
this.access = options.access;
|
|
4692
|
+
this.match = compileFilter(options.filters, {
|
|
4693
|
+
me: options.me,
|
|
4694
|
+
actors: options.actors,
|
|
4695
|
+
messages: this.messages,
|
|
4696
|
+
access: options.access
|
|
4697
|
+
});
|
|
4698
|
+
this.criteria = hasCriteria(options.filters);
|
|
4699
|
+
this.all = options.all;
|
|
4629
4700
|
}
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
}
|
|
4639
|
-
const
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
if (!own(state, event.payload.channel)) setOwn(state, event.payload.channel, emptyChannel(event.payload.channel));
|
|
4652
|
-
return state;
|
|
4701
|
+
/** Loads what `events` touch, all as of `index`, in two queries rather than two per event. */
|
|
4702
|
+
async preload(events, index) {
|
|
4703
|
+
const ids = /* @__PURE__ */ new Set();
|
|
4704
|
+
for (const event of events) {
|
|
4705
|
+
const id = concernedMessageId(event);
|
|
4706
|
+
if (id === null) continue;
|
|
4707
|
+
if (event.type !== "message.posted") ids.add(id);
|
|
4708
|
+
else if (event.payload.re !== null) ids.add(event.payload.re);
|
|
4709
|
+
}
|
|
4710
|
+
const load = async (wanted) => {
|
|
4711
|
+
if (wanted.length === 0) return;
|
|
4712
|
+
const found = await this.reads.messagesAt(wanted, index);
|
|
4713
|
+
for (const id of wanted) {
|
|
4714
|
+
this.loaded.add(id);
|
|
4715
|
+
const message = found.get(id);
|
|
4716
|
+
if (message) this.messages.byId[id] = message;
|
|
4717
|
+
}
|
|
4718
|
+
};
|
|
4719
|
+
await load([...ids].filter((id) => !this.loaded.has(id) && id <= index));
|
|
4720
|
+
const roots = Object.values(this.messages.byId).flatMap((message) => message.re === null ? [] : [message.re]);
|
|
4721
|
+
await load([...new Set(roots)].filter((id) => !this.loaded.has(id)));
|
|
4653
4722
|
}
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4723
|
+
async step(event, signal) {
|
|
4724
|
+
await loadInto(this.reads, this.messages, this.loaded, event, signal);
|
|
4725
|
+
const { id, before, after } = foldEvent(this.messages, this.actors, event);
|
|
4726
|
+
const message = after ?? before;
|
|
4727
|
+
const readable = id === null ? this.access.readsAll : message !== void 0 && this.access.readable(message.channel);
|
|
4728
|
+
const hidden = HIDDEN.has(event.type) && !this.all;
|
|
4729
|
+
if (!(readable && !hidden && (this.criteria ? this.match(before) || this.match(after) : id !== null || this.all))) return {
|
|
4730
|
+
index: event.index,
|
|
4731
|
+
view: null
|
|
4732
|
+
};
|
|
4733
|
+
await this.loadLinked([...after?.links ?? [], ...event.payload.links ?? []], event.index, signal);
|
|
4734
|
+
const reader = {
|
|
4735
|
+
access: this.access,
|
|
4736
|
+
channelOf: (message) => this.messages.byId[message]?.channel ?? this.linked.get(message)
|
|
4737
|
+
};
|
|
4738
|
+
return {
|
|
4739
|
+
index: event.index,
|
|
4740
|
+
view: eventView(event, after, this.actors, reader)
|
|
4741
|
+
};
|
|
4668
4742
|
}
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4743
|
+
/** Where the messages `links` point to live; a message never moves, so any version says. */
|
|
4744
|
+
async loadLinked(links, index, signal) {
|
|
4745
|
+
if (this.access.readsAll) return;
|
|
4746
|
+
const wanted = [...new Set(linkedIds(links))].filter((id) => !this.messages.byId[id] && !this.linked.has(id));
|
|
4747
|
+
if (wanted.length === 0) return;
|
|
4748
|
+
const found = await this.reads.messagesAt(wanted, index, signal);
|
|
4749
|
+
for (const id of wanted) this.linked.set(id, found.get(id)?.channel);
|
|
4750
|
+
}
|
|
4751
|
+
};
|
|
4752
|
+
/** Resolves when the iterator yields, or with null once the signal aborts. */
|
|
4753
|
+
function nextOrAbort(iterator, signal) {
|
|
4754
|
+
if (signal.aborted) return Promise.resolve(null);
|
|
4755
|
+
return new Promise((resolve, reject) => {
|
|
4756
|
+
const onAbort = () => resolve(null);
|
|
4757
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
4758
|
+
iterator.next().then((result) => {
|
|
4759
|
+
signal.removeEventListener("abort", onAbort);
|
|
4760
|
+
resolve(result);
|
|
4761
|
+
}, (error) => {
|
|
4762
|
+
signal.removeEventListener("abort", onAbort);
|
|
4763
|
+
reject(error);
|
|
4764
|
+
});
|
|
4765
|
+
});
|
|
4766
|
+
}
|
|
4767
|
+
/** Where a feed starts: `after`, or the head when it's omitted or past it. */
|
|
4768
|
+
async function start(options) {
|
|
4769
|
+
const { index: head } = await options.session.state(channelsReducer);
|
|
4770
|
+
return options.after === void 0 || options.after >= head ? head : options.after;
|
|
4771
|
+
}
|
|
4772
|
+
const PAGE = 200;
|
|
4773
|
+
/**
|
|
4774
|
+
* One long-poll: matching events already in the log return at once; otherwise
|
|
4775
|
+
* it waits up to `waitMs` for the first new match. The cursor is the last
|
|
4776
|
+
* event examined, matched or not, so the next poll never rescans.
|
|
4777
|
+
*/
|
|
4778
|
+
async function pollFeed(options, waitMs, signal) {
|
|
4779
|
+
const index = await start(options);
|
|
4780
|
+
const feed = new FeedProjection(options);
|
|
4781
|
+
const events = [];
|
|
4782
|
+
let cursor = index;
|
|
4783
|
+
const backlog = await options.session.history({
|
|
4784
|
+
gte: index + 1,
|
|
4785
|
+
lte: index + PAGE
|
|
4786
|
+
});
|
|
4787
|
+
await feed.preload(backlog, index);
|
|
4788
|
+
for (const event of backlog) {
|
|
4789
|
+
const item = await feed.step(event, signal);
|
|
4790
|
+
cursor = item.index;
|
|
4791
|
+
if (item.view) events.push(item.view);
|
|
4792
|
+
}
|
|
4793
|
+
if (events.length > 0 || backlog.length === PAGE || waitMs <= 0) return {
|
|
4794
|
+
events,
|
|
4795
|
+
cursor
|
|
4681
4796
|
};
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4797
|
+
const timeout = AbortSignal.timeout(waitMs);
|
|
4798
|
+
const until = AbortSignal.any([signal, timeout]);
|
|
4799
|
+
const iterator = options.session.stream({ startAfter: cursor })[Symbol.asyncIterator]();
|
|
4800
|
+
try {
|
|
4801
|
+
while (true) {
|
|
4802
|
+
const next = await nextOrAbort(iterator, until);
|
|
4803
|
+
if (next === null || next.done) return {
|
|
4804
|
+
events,
|
|
4805
|
+
cursor
|
|
4806
|
+
};
|
|
4807
|
+
const item = await feed.step(next.value, until);
|
|
4808
|
+
cursor = item.index;
|
|
4809
|
+
if (item.view) {
|
|
4810
|
+
events.push(item.view);
|
|
4695
4811
|
return {
|
|
4696
|
-
|
|
4697
|
-
|
|
4812
|
+
events,
|
|
4813
|
+
cursor
|
|
4698
4814
|
};
|
|
4699
|
-
} catch {
|
|
4700
|
-
return null;
|
|
4701
4815
|
}
|
|
4702
4816
|
}
|
|
4703
|
-
}
|
|
4704
|
-
|
|
4705
|
-
const dataKey = (id) => `board/attachments/${id}`;
|
|
4706
|
-
/** A direct upload the board signed, until it's finished: what it's called, and who may finish it. */
|
|
4707
|
-
const ticketKey = (id) => `board/uploads/${id}.json`;
|
|
4708
|
-
const metaKey = (id) => `board/attachments/${id}.json`;
|
|
4709
|
-
/** A board without a blob store keeps no files: every file route says so. */
|
|
4710
|
-
const noBlob = () => new HttpError(501, "no_files", "this board keeps no files");
|
|
4711
|
-
/** 128 random bits, base64url, drawn again when they'd start with `-`, which a command line reads as a flag. */
|
|
4712
|
-
function attachmentId() {
|
|
4713
|
-
for (;;) {
|
|
4714
|
-
const id = randomBytes(16).toString("base64url");
|
|
4715
|
-
if (!id.startsWith("-")) return id;
|
|
4817
|
+
} finally {
|
|
4818
|
+
iterator.return?.();
|
|
4716
4819
|
}
|
|
4717
4820
|
}
|
|
4821
|
+
//#endregion
|
|
4822
|
+
//#region src/server/writes.ts
|
|
4823
|
+
/** A piece of the board's own deployment, writing as `actor` with full access. */
|
|
4824
|
+
function deploymentIdentity(actor, handle) {
|
|
4825
|
+
return {
|
|
4826
|
+
principal: {
|
|
4827
|
+
id: actor,
|
|
4828
|
+
kind: "deployment",
|
|
4829
|
+
handle,
|
|
4830
|
+
access: FULL_ACCESS,
|
|
4831
|
+
expiresAt: null
|
|
4832
|
+
},
|
|
4833
|
+
author: {
|
|
4834
|
+
actor,
|
|
4835
|
+
principal: actor,
|
|
4836
|
+
profile: null,
|
|
4837
|
+
session: null
|
|
4838
|
+
},
|
|
4839
|
+
actor: {
|
|
4840
|
+
id: actor,
|
|
4841
|
+
kind: "deployment",
|
|
4842
|
+
handle,
|
|
4843
|
+
name: handle,
|
|
4844
|
+
avatar: null
|
|
4845
|
+
}
|
|
4846
|
+
};
|
|
4847
|
+
}
|
|
4718
4848
|
/**
|
|
4719
|
-
*
|
|
4720
|
-
*
|
|
4721
|
-
*
|
|
4722
|
-
*
|
|
4849
|
+
* The `actor.seen` a write carries, or null: who its author is, as the board's record of them
|
|
4850
|
+
* says, unless the board knows that already. A platform user's record is board-wide, so a write
|
|
4851
|
+
* whose identity doesn't keep it (`records: false`) leaves it as it is. A host's principal and its
|
|
4852
|
+
* profiles are recorded as the host's, which sync never writes as.
|
|
4723
4853
|
*/
|
|
4724
|
-
function
|
|
4725
|
-
if (
|
|
4726
|
-
return
|
|
4854
|
+
function seenFor(identity, actors) {
|
|
4855
|
+
if (identity.records === false) return null;
|
|
4856
|
+
return actorSeen(identity.actor, actors, identity.principal.facts?.issuer === "host");
|
|
4727
4857
|
}
|
|
4858
|
+
/** The actors a write can mention: the ones the board knows, plus the ones an email named. */
|
|
4859
|
+
const knownWith = (actors, found) => found.length === 0 ? actors : {
|
|
4860
|
+
...actors,
|
|
4861
|
+
byId: {
|
|
4862
|
+
...actors.byId,
|
|
4863
|
+
...Object.fromEntries(found.map((a) => [a.id, a]))
|
|
4864
|
+
}
|
|
4865
|
+
};
|
|
4866
|
+
const messageNotFound = (id) => () => notFound(`message not found: #${id}`, "message_not_found");
|
|
4728
4867
|
/**
|
|
4729
|
-
*
|
|
4730
|
-
*
|
|
4731
|
-
*
|
|
4732
|
-
* `max` is the most it can be: `ATTACHMENT_BYTES_MAX` unless the board's own sync imports it.
|
|
4868
|
+
* A message the board looked up and the caller may act on with `permission`,
|
|
4869
|
+
* proved against its own channel. A message they can't read answers 404, as if
|
|
4870
|
+
* it didn't exist: IDs are sequential, so a 403 would confirm it does.
|
|
4733
4871
|
*/
|
|
4734
|
-
async function
|
|
4735
|
-
|
|
4736
|
-
if (
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
|
|
4740
|
-
name: fileName(input.name),
|
|
4741
|
-
type: mediaType(input.type),
|
|
4742
|
-
size: input.data.byteLength
|
|
4743
|
-
};
|
|
4744
|
-
await blob.put(dataKey(attachment.id), input.data, attachment.type);
|
|
4745
|
-
const meta = input.uploadedBy === void 0 ? attachment : {
|
|
4746
|
-
...attachment,
|
|
4747
|
-
uploadedBy: input.uploadedBy,
|
|
4748
|
-
...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {}
|
|
4872
|
+
async function authorizeMessage(ctx, access, permission, id) {
|
|
4873
|
+
const message = await ctx.reads.message(id);
|
|
4874
|
+
if (!message) throw messageNotFound(id)();
|
|
4875
|
+
return {
|
|
4876
|
+
message,
|
|
4877
|
+
proof: authorize(access, permission, message.channel, messageNotFound(id))
|
|
4749
4878
|
};
|
|
4750
|
-
await blob.put(metaKey(attachment.id), new TextEncoder().encode(JSON.stringify(meta)), "application/json");
|
|
4751
|
-
return attachment;
|
|
4752
4879
|
}
|
|
4753
|
-
|
|
4754
|
-
|
|
4880
|
+
/**
|
|
4881
|
+
* Your own message, to edit or delete: `post` in its channel. Where you can't
|
|
4882
|
+
* read, it's yours only if it was posted without reading too: a write-only
|
|
4883
|
+
* source fixes what it wrote, but a principal ID it shares with a caller that
|
|
4884
|
+
* reads (a repo's workflows share one) doesn't reach that caller's messages.
|
|
4885
|
+
* A board token that pins a profile owns only what was written as it (`wroteAs`).
|
|
4886
|
+
* Someone else's answers 404 where you can't read it, and 403 where you can.
|
|
4887
|
+
*/
|
|
4888
|
+
async function authorizeOwn(ctx, identity, id, verb) {
|
|
4889
|
+
const { principal } = identity;
|
|
4890
|
+
const message = await ctx.reads.message(id);
|
|
4891
|
+
if (!message) throw messageNotFound(id)();
|
|
4892
|
+
const readable = principal.access.readable(message.channel);
|
|
4893
|
+
if (!wroteAs(identity, message.by) || !readable && !message.blind) {
|
|
4894
|
+
if (!readable) throw messageNotFound(id)();
|
|
4895
|
+
throw forbidden$1(`only the author can ${verb} a message`);
|
|
4896
|
+
}
|
|
4897
|
+
return {
|
|
4898
|
+
message,
|
|
4899
|
+
proof: authorize(principal.access, "post", message.channel)
|
|
4900
|
+
};
|
|
4755
4901
|
}
|
|
4756
|
-
const
|
|
4902
|
+
const hasLabels = (labels) => Object.keys(labels ?? {}).length > 0;
|
|
4757
4903
|
/**
|
|
4758
|
-
*
|
|
4759
|
-
*
|
|
4760
|
-
*
|
|
4904
|
+
* Proofs for a post. A root lands in the channel it names, which the caller
|
|
4905
|
+
* needn't read: write-only is `['post']`. A reply lands in its root's channel,
|
|
4906
|
+
* looked up here and never taken from the request, and needs `read` there too,
|
|
4907
|
+
* since addressing a thread you can't see would confirm it exists.
|
|
4761
4908
|
*/
|
|
4762
|
-
async function
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
if (
|
|
4766
|
-
|
|
4767
|
-
|
|
4909
|
+
async function authorizePost(ctx, access, input) {
|
|
4910
|
+
let channel;
|
|
4911
|
+
let re;
|
|
4912
|
+
if (input.re !== void 0) {
|
|
4913
|
+
re = (await authorizeMessage(ctx, access, "read", input.re)).message;
|
|
4914
|
+
channel = re.channel;
|
|
4915
|
+
} else {
|
|
4916
|
+
if (!input.channel) throw badRequest("a post needs a channel");
|
|
4917
|
+
channel = input.channel;
|
|
4918
|
+
}
|
|
4768
4919
|
return {
|
|
4769
|
-
|
|
4770
|
-
|
|
4771
|
-
|
|
4920
|
+
post: authorize(access, "post", channel),
|
|
4921
|
+
...re ? { re } : {},
|
|
4922
|
+
...hasLabels(input.labels) ? { label: authorize(access, "label", channel) } : {},
|
|
4923
|
+
...input.sync?.length ? { sync: authorize(access, "sync", channel) } : {}
|
|
4772
4924
|
};
|
|
4773
4925
|
}
|
|
4774
|
-
/**
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4926
|
+
/**
|
|
4927
|
+
* Spends a proof on its target: a write checked against one channel can't land
|
|
4928
|
+
* in another. A mismatch is the board's own bug, never the caller's.
|
|
4929
|
+
*/
|
|
4930
|
+
function spend(proof, permission, target) {
|
|
4931
|
+
if (!proof || proof.permission !== permission || proof.channel !== target.channel) throw new Error(`a ${permission} write in ${target.channel} needs a proof for that channel`);
|
|
4932
|
+
}
|
|
4933
|
+
/** Full-access proofs for the board's own code (sync), still checked against the channel each write lands in. */
|
|
4934
|
+
const trusted = {
|
|
4935
|
+
message: (ctx, permission, id) => authorizeMessage(ctx, FULL_ACCESS, permission, id),
|
|
4936
|
+
post: (ctx, input) => authorizePost(ctx, FULL_ACCESS, input)
|
|
4937
|
+
};
|
|
4938
|
+
async function writePost(ctx, input) {
|
|
4939
|
+
const { identity } = input;
|
|
4940
|
+
const sent = input.text;
|
|
4941
|
+
let channel = input.channel;
|
|
4942
|
+
let re = null;
|
|
4943
|
+
let replyTo = null;
|
|
4944
|
+
let thread;
|
|
4945
|
+
const id = input.id ?? (input.re === void 0 ? crypto.randomUUID() : void 0);
|
|
4946
|
+
if (input.re !== void 0) {
|
|
4947
|
+
const target = input.proofs.re;
|
|
4948
|
+
if (target?.id !== input.re) throw new Error(`a reply to #${input.re} needs proofs for that message`);
|
|
4949
|
+
re = target.re ?? target.id;
|
|
4950
|
+
replyTo = target.id === re ? null : target.id;
|
|
4951
|
+
channel = target.channel;
|
|
4952
|
+
thread = target.thread;
|
|
4953
|
+
if (input.sync?.length) throw badRequest("sync attaches whole threads: use `board sync <id> <target>`");
|
|
4954
|
+
} else {
|
|
4955
|
+
if (!channel) throw badRequest("a post needs a channel");
|
|
4956
|
+
if (input.after !== void 0) throw badRequest("`after` is for replies", "invalid_after");
|
|
4957
|
+
thread = id;
|
|
4958
|
+
}
|
|
4959
|
+
spend(input.proofs.post, "post", { channel });
|
|
4960
|
+
if (hasLabels(input.labels)) spend(input.proofs.label, "label", { channel });
|
|
4961
|
+
if (input.sync?.length) spend(input.proofs.sync, "sync", { channel });
|
|
4962
|
+
const replayed = await replayOf(ctx, input, {
|
|
4963
|
+
channel,
|
|
4964
|
+
re,
|
|
4965
|
+
replyTo
|
|
4966
|
+
}, sent);
|
|
4967
|
+
if (replayed) return replayed;
|
|
4968
|
+
if (input.after !== void 0) {
|
|
4969
|
+
if ((await ctx.reads.message(input.after))?.thread !== thread) throw badRequest(`after names no message in #${re}'s thread`, "invalid_after");
|
|
4970
|
+
}
|
|
4971
|
+
return commitPost(ctx, input, {
|
|
4972
|
+
channel,
|
|
4973
|
+
re,
|
|
4974
|
+
replyTo,
|
|
4975
|
+
thread,
|
|
4976
|
+
id,
|
|
4977
|
+
sent
|
|
4978
|
+
});
|
|
4979
|
+
}
|
|
4980
|
+
/** The post a caller's own ID already landed, as its retry gets it back: null when there's none. */
|
|
4981
|
+
async function replayOf(ctx, input, place, sent) {
|
|
4982
|
+
if (input.id === void 0) return null;
|
|
4983
|
+
const landed = await ctx.reads.byEventId(input.id);
|
|
4984
|
+
if (!landed) return null;
|
|
4985
|
+
if (landed.channel !== place.channel || landed.re !== place.re || landed.replyTo !== place.replyTo) throw duplicateId();
|
|
4986
|
+
const shown = await landedFor(ctx, input.identity, landed);
|
|
4987
|
+
if (!shown) throw duplicateId();
|
|
4988
|
+
return shownTo(shown, input.identity.principal.access, sent);
|
|
4780
4989
|
}
|
|
4781
|
-
/** How long a direct upload's URL takes bytes: long enough for 100 MB on a slow link. */
|
|
4782
|
-
const DIRECT_UPLOAD_TTL_MS = 18e5;
|
|
4783
|
-
const noDirectUploads = () => new HttpError(501, "no_direct_uploads", `this board's blob store can't take direct uploads, so files are at most ${ATTACHMENT_BYTES_MAX / 1024 / 1024} MB`);
|
|
4784
4990
|
/**
|
|
4785
|
-
*
|
|
4786
|
-
*
|
|
4991
|
+
* A post that landed, as its author may have it back: only the same author's, and one in a
|
|
4992
|
+
* channel it can't read only if it posted without reading too. A caller that can't read gets back
|
|
4993
|
+
* what it sent, as it landed: never what others have added since. Null for anyone else.
|
|
4787
4994
|
*/
|
|
4788
|
-
async function
|
|
4789
|
-
if (!
|
|
4790
|
-
|
|
4791
|
-
|
|
4792
|
-
|
|
4793
|
-
|
|
4794
|
-
|
|
4795
|
-
|
|
4796
|
-
|
|
4797
|
-
size: input.size,
|
|
4798
|
-
uploadedBy: input.uploadedBy,
|
|
4799
|
-
...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {},
|
|
4800
|
-
expiresAt: expires.toISOString()
|
|
4801
|
-
};
|
|
4802
|
-
await blob.put(ticketKey(ticket.id), new TextEncoder().encode(JSON.stringify(ticket)), "application/json");
|
|
4803
|
-
const { url, headers } = await blob.uploadUrl(dataKey(ticket.id), {
|
|
4804
|
-
contentType: ticket.type,
|
|
4805
|
-
maxBytes: ticket.size,
|
|
4806
|
-
expiresAt: expires
|
|
4995
|
+
async function landedFor(ctx, identity, landed) {
|
|
4996
|
+
if (!sameAuthor(landed.by, identity.author)) return null;
|
|
4997
|
+
const { access } = identity.principal;
|
|
4998
|
+
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
4999
|
+
if (access.readable(landed.channel)) return view(landed, actors, await readerFor(ctx, access, landed));
|
|
5000
|
+
if (!landed.blind) return null;
|
|
5001
|
+
const [event] = await ctx.session.history({
|
|
5002
|
+
gte: landed.id,
|
|
5003
|
+
lte: landed.id
|
|
4807
5004
|
});
|
|
5005
|
+
const posted = foldMessages({
|
|
5006
|
+
byId: {},
|
|
5007
|
+
replies: {}
|
|
5008
|
+
}, event).byId[landed.id];
|
|
4808
5009
|
return {
|
|
4809
|
-
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
...headers,
|
|
4813
|
-
"content-type": ticket.type
|
|
4814
|
-
},
|
|
4815
|
-
expiresAt: ticket.expiresAt
|
|
5010
|
+
...view(posted, actors, await readerFor(ctx, access, posted)),
|
|
5011
|
+
text: blindText(posted.text, identity.actor.id),
|
|
5012
|
+
mentions: []
|
|
4816
5013
|
};
|
|
4817
5014
|
}
|
|
4818
5015
|
/**
|
|
4819
|
-
*
|
|
4820
|
-
*
|
|
4821
|
-
*
|
|
4822
|
-
* cache (Vercel Blob's CDN) would keep that miss, and the post that names the file would find nothing.
|
|
5016
|
+
* A message's text for its writer where it can't read: each exact mention but of itself shows as
|
|
5017
|
+
* `@…`. The board may have turned an email it wrote into an actor ID, and who that is, `/actors`
|
|
5018
|
+
* doesn't show it either.
|
|
4823
5019
|
*/
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
const
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
const
|
|
4831
|
-
if (
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
}
|
|
5020
|
+
const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
|
|
5021
|
+
const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile && a.session === b.session;
|
|
5022
|
+
async function commitPost(ctx, input, placed) {
|
|
5023
|
+
const { identity } = input;
|
|
5024
|
+
const { channel, re, replyTo, thread, id, sent } = placed;
|
|
5025
|
+
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5026
|
+
const targets = [];
|
|
5027
|
+
if (re === null) for (const requested of input.sync ?? []) {
|
|
5028
|
+
const target = syncTarget(requested);
|
|
5029
|
+
await unclaimed(ctx, target, thread, identity.principal.access);
|
|
5030
|
+
if (!targets.some((t) => t.target === target.target)) targets.push({
|
|
5031
|
+
...target,
|
|
5032
|
+
cause: "request"
|
|
5033
|
+
});
|
|
5034
|
+
}
|
|
5035
|
+
const seen = seenFor(identity, actors);
|
|
5036
|
+
const { text, found } = await withEmailMentions(input.text);
|
|
5037
|
+
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
5038
|
+
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? identity.actor : void 0, input.lenientMentions ?? false, identity.principal.access.readsAll);
|
|
5039
|
+
const synced = await Promise.all(targets.map(async ({ target, kind, cause }) => ({
|
|
5040
|
+
type: "thread.synced",
|
|
5041
|
+
id: await derivedId("board", thread, "sync", target),
|
|
5042
|
+
payload: {
|
|
5043
|
+
thread,
|
|
5044
|
+
target,
|
|
5045
|
+
kind,
|
|
5046
|
+
cause,
|
|
5047
|
+
by: identity.author
|
|
5048
|
+
}
|
|
5049
|
+
})));
|
|
5050
|
+
const events = [
|
|
5051
|
+
...seen ? [seen] : [],
|
|
5052
|
+
...named,
|
|
5053
|
+
{
|
|
5054
|
+
type: "message.posted",
|
|
5055
|
+
...id ? { id } : {},
|
|
5056
|
+
payload: {
|
|
5057
|
+
channel,
|
|
5058
|
+
text,
|
|
5059
|
+
re,
|
|
5060
|
+
replyTo,
|
|
5061
|
+
thread,
|
|
5062
|
+
labels: input.labels ?? {},
|
|
5063
|
+
noSync: input.noSync ?? false,
|
|
5064
|
+
mentions,
|
|
5065
|
+
by: identity.author,
|
|
5066
|
+
origin: input.origin ?? null,
|
|
5067
|
+
from: input.from ?? null,
|
|
5068
|
+
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
5069
|
+
...input.links?.length ? { links: input.links } : {},
|
|
5070
|
+
...input.schedule ? { schedule: input.schedule } : {},
|
|
5071
|
+
...identity.principal.access.readable(channel) ? {} : { blind: true },
|
|
5072
|
+
...input.importedBy !== void 0 ? { importedBy: input.importedBy } : {}
|
|
5073
|
+
}
|
|
5074
|
+
},
|
|
5075
|
+
...synced
|
|
5076
|
+
];
|
|
5077
|
+
let rows;
|
|
4839
5078
|
try {
|
|
4840
|
-
|
|
4841
|
-
uploadedBy: ticket.uploadedBy,
|
|
4842
|
-
...ticket.uploadedWith ? { uploadedWith: ticket.uploadedWith } : {}
|
|
4843
|
-
};
|
|
4844
|
-
await blob.put(metaKey(id), new TextEncoder().encode(JSON.stringify({
|
|
4845
|
-
...attachment,
|
|
4846
|
-
...uploader
|
|
4847
|
-
})), "application/json");
|
|
5079
|
+
rows = input.after === void 0 || re === null ? await ctx.session.append(...events) : await appendWhile(ctx, nothingAfter(ctx, re, input.after), events);
|
|
4848
5080
|
} catch (error) {
|
|
4849
|
-
const
|
|
4850
|
-
|
|
4851
|
-
|
|
5081
|
+
const replayed = error instanceof HttpError && error.code === "newer_message" ? await replayOf(ctx, input, {
|
|
5082
|
+
channel,
|
|
5083
|
+
re,
|
|
5084
|
+
replyTo
|
|
5085
|
+
}, sent) : null;
|
|
5086
|
+
if (replayed) return replayed;
|
|
5087
|
+
throw error;
|
|
4852
5088
|
}
|
|
4853
|
-
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
return
|
|
4867
|
-
kind: author.kind,
|
|
4868
|
-
handle: author.handle,
|
|
4869
|
-
name: author.name,
|
|
4870
|
-
avatar: author.avatar
|
|
4871
|
-
};
|
|
5089
|
+
const posted = rows.find((row) => row.type === "message.posted");
|
|
5090
|
+
await untilApplied(ctx, rows);
|
|
5091
|
+
const message = foldMessages({
|
|
5092
|
+
byId: {},
|
|
5093
|
+
replies: {}
|
|
5094
|
+
}, posted).byId[posted.index];
|
|
5095
|
+
const known = seen ? {
|
|
5096
|
+
...actors,
|
|
5097
|
+
byId: {
|
|
5098
|
+
...actors.byId,
|
|
5099
|
+
[identity.actor.id]: identity.actor
|
|
5100
|
+
}
|
|
5101
|
+
} : actors;
|
|
5102
|
+
return shownTo(view(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent, unknown);
|
|
4872
5103
|
}
|
|
4873
|
-
/** The board's own code, which reads every channel: it needs no messages to say so. */
|
|
4874
|
-
const OWN_CODE = {
|
|
4875
|
-
access: FULL_ACCESS,
|
|
4876
|
-
channelOf: () => void 0
|
|
4877
|
-
};
|
|
4878
|
-
/** The board messages `links` point to, for `Reader.channelOf`. */
|
|
4879
|
-
const linkedIds = (links) => links.flatMap((link) => link.message === null ? [] : [link.message]);
|
|
4880
5104
|
/**
|
|
4881
|
-
*
|
|
4882
|
-
* it
|
|
4883
|
-
*
|
|
5105
|
+
* A post's view for its writer. One that can't read the channel gets back the
|
|
5106
|
+
* text it sent, no mentions, and no `unknownMentions`: the board resolved its
|
|
5107
|
+
* handles and emails to actor IDs, which `/actors` doesn't show it, and which
|
|
5108
|
+
* handles matched no one would say which ones exist. The board keeps the
|
|
5109
|
+
* mentions, so they still notify.
|
|
4884
5110
|
*/
|
|
4885
|
-
|
|
4886
|
-
|
|
4887
|
-
|
|
4888
|
-
|
|
4889
|
-
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
4893
|
-
|
|
4894
|
-
|
|
4895
|
-
} : {
|
|
4896
|
-
url: link.url,
|
|
4897
|
-
message: null,
|
|
4898
|
-
snapshot: null,
|
|
4899
|
-
unavailable: "not_readable"
|
|
4900
|
-
};
|
|
4901
|
-
});
|
|
4902
|
-
}
|
|
4903
|
-
/** The links in an event view: its payload's, its message's, and the message before a label change. */
|
|
4904
|
-
const viewLinks = (view) => {
|
|
4905
|
-
const { payload, message, before } = view;
|
|
4906
|
-
return [
|
|
4907
|
-
payload?.links,
|
|
4908
|
-
message?.links,
|
|
4909
|
-
before?.links
|
|
4910
|
-
].filter((links) => links !== void 0);
|
|
4911
|
-
};
|
|
4912
|
-
/** The board messages an event view's links point to, for a reader of them. */
|
|
4913
|
-
const viewLinkedIds = (view) => viewLinks(view).flatMap((links) => links.flatMap((link) => link.message === null ? [] : [indexOf(link.message) ?? 0]));
|
|
5111
|
+
const shownTo = (shown, access, sent, unknown = []) => !access.readable(shown.channel) ? {
|
|
5112
|
+
...shown,
|
|
5113
|
+
text: sent,
|
|
5114
|
+
mentions: []
|
|
5115
|
+
} : unknown.length ? {
|
|
5116
|
+
...shown,
|
|
5117
|
+
unknownMentions: unknown
|
|
5118
|
+
} : shown;
|
|
5119
|
+
/** The writer, as the reader of the view its write returns. Only a link to a board message needs a lookup. */
|
|
5120
|
+
const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
|
|
4914
5121
|
/**
|
|
4915
|
-
*
|
|
4916
|
-
*
|
|
4917
|
-
*
|
|
5122
|
+
* Refuses an external thread another board thread is synced with: taking it
|
|
5123
|
+
* over would send its replies away from that thread, to a caller who may not
|
|
5124
|
+
* read it. A reader of that thread's channel learns which thread it is. It
|
|
5125
|
+
* reads the tables once they've applied the whole log, so a sync just made
|
|
5126
|
+
* counts.
|
|
4918
5127
|
*/
|
|
4919
|
-
function
|
|
4920
|
-
if (
|
|
4921
|
-
|
|
4922
|
-
const
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
4927
|
-
if (shown.message) shown.message.links = reread(shown.message.links);
|
|
4928
|
-
if (shown.before) shown.before.links = reread(shown.before.links);
|
|
4929
|
-
return shown;
|
|
5128
|
+
async function unclaimed(ctx, target, thread, access) {
|
|
5129
|
+
if (target.kind !== "thread") return;
|
|
5130
|
+
await ctx.reads.ensure();
|
|
5131
|
+
const owner = await ctx.reads.tables.threadOf(target.target);
|
|
5132
|
+
if (owner === null || owner === thread) return;
|
|
5133
|
+
const synced = await ctx.reads.tables.syncOf(owner);
|
|
5134
|
+
const which = synced && access.readable(synced.channel) ? `#${synced.root}` : "another thread";
|
|
5135
|
+
throw new HttpError(409, "already_synced", `${target.target} is already synced with ${which}`);
|
|
4930
5136
|
}
|
|
4931
|
-
/**
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
4938
|
-
|
|
4939
|
-
const
|
|
4940
|
-
|
|
4941
|
-
|
|
4942
|
-
|
|
4943
|
-
|
|
4944
|
-
|
|
4945
|
-
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
...schedule ? { schedule: {
|
|
4949
|
-
id: scheduleRef(schedule.id),
|
|
4950
|
-
n: schedule.n
|
|
4951
|
-
} } : {},
|
|
4952
|
-
links: readableLinks(message.links, reader),
|
|
4953
|
-
labels: { ...message.labels },
|
|
4954
|
-
reactions: Object.fromEntries(Object.entries(message.reactions).map(([emoji, ids]) => [emoji, [...ids]])),
|
|
4955
|
-
author: actorView(actors, message.by.actor)
|
|
4956
|
-
};
|
|
5137
|
+
/**
|
|
5138
|
+
* Waits until the tables hold a write, so any read after it includes it. Most often
|
|
5139
|
+
* nothing was written in between, and the writer applies its own events itself; else
|
|
5140
|
+
* it waits for the tables' consumer. The write landed either way: if the tables are
|
|
5141
|
+
* slow or stuck, it still succeeds.
|
|
5142
|
+
*/
|
|
5143
|
+
async function untilApplied(ctx, rows) {
|
|
5144
|
+
const events = [...rows].sort((a, b) => a.index - b.index);
|
|
5145
|
+
const last = events.at(-1).index;
|
|
5146
|
+
try {
|
|
5147
|
+
let caughtUp = true;
|
|
5148
|
+
for (const event of events) if (!(caughtUp = await ctx.reads.tables.applyNext(event))) break;
|
|
5149
|
+
if (caughtUp) return;
|
|
5150
|
+
} catch {}
|
|
5151
|
+
await ctx.reads.ensure(last, AbortSignal.timeout(LANDED_WAIT_MS)).catch((error) => {
|
|
5152
|
+
console.warn(`[board] the tables haven't applied #${last} yet:`, error.message);
|
|
5153
|
+
});
|
|
4957
5154
|
}
|
|
4958
|
-
|
|
5155
|
+
/** How long a write waits for the tables before it answers anyway. */
|
|
5156
|
+
const LANDED_WAIT_MS = 1e4;
|
|
4959
5157
|
/**
|
|
4960
|
-
*
|
|
4961
|
-
*
|
|
4962
|
-
*
|
|
5158
|
+
* Appends `events` only while the board, as `holds` reads it, still allows them: `holds` checks
|
|
5159
|
+
* the tables, throws what refuses the write, and returns the index its reads reflect. The append
|
|
5160
|
+
* holds only while that index is still the log's last, so anything that lands in between,
|
|
5161
|
+
* anywhere on the board, moves it, and it looks again from there.
|
|
4963
5162
|
*/
|
|
4964
|
-
function
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
};
|
|
5163
|
+
async function appendWhile(ctx, holds, events) {
|
|
5164
|
+
return whileHeadMoves(async () => {
|
|
5165
|
+
await ctx.reads.ensure();
|
|
5166
|
+
return appendIfLast(ctx.session, await holds(), events);
|
|
5167
|
+
});
|
|
4970
5168
|
}
|
|
4971
|
-
/** Whether `author` is one of `who`: its actor, or an agent of one of its people. */
|
|
4972
|
-
const covers = (who, actor, principal) => who.actors.has(actor) || principal !== void 0 && who.principals.has(principal);
|
|
4973
|
-
const hasLabel = (labels, [key, values]) => Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
|
|
4974
5169
|
/**
|
|
4975
|
-
*
|
|
4976
|
-
*
|
|
4977
|
-
* labels, so `pr=…` means the PR's whole conversation. `messages` is the live
|
|
4978
|
-
* state for that lookup. A message in a channel `access` can't read never
|
|
4979
|
-
* matches, whatever the filters say.
|
|
5170
|
+
* Runs `attempt`, a look and a conditional append, again each time the board moves on in
|
|
5171
|
+
* between, up to `CONDITIONAL_TRIES` times: how every conditional write here looks again.
|
|
4980
5172
|
*/
|
|
4981
|
-
function
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
|
|
4985
|
-
|
|
4986
|
-
|
|
4987
|
-
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
5173
|
+
async function whileHeadMoves(attempt) {
|
|
5174
|
+
for (let tries = 1;; tries++) try {
|
|
5175
|
+
return await attempt();
|
|
5176
|
+
} catch (error) {
|
|
5177
|
+
if (!headMoved(error)) throw error;
|
|
5178
|
+
if (tries === CONDITIONAL_TRIES) throw new HttpError(503, "unavailable", "the board kept changing while it checked: try again");
|
|
5179
|
+
await new Promise((resolve) => setTimeout(resolve, Math.random() * 5 * tries));
|
|
5180
|
+
}
|
|
5181
|
+
}
|
|
5182
|
+
/** How many times a conditional write looks again, as the board moves on, before it gives up. */
|
|
5183
|
+
const CONDITIONAL_TRIES = 10;
|
|
5184
|
+
/** A reply's `after`: nothing came after it in the thread, as of the index the read reflects. */
|
|
5185
|
+
const nothingAfter = (ctx, root, after) => async () => {
|
|
5186
|
+
const { messages: [newer], position } = await ctx.reads.tables.messages({ re: root }, {
|
|
5187
|
+
after,
|
|
5188
|
+
limit: 1
|
|
5189
|
+
});
|
|
5190
|
+
if (newer) throw new HttpError(409, "newer_message", `#${newer.id} came after #${after}`);
|
|
5191
|
+
return position;
|
|
5192
|
+
};
|
|
5193
|
+
/** The message a by-ID write targets, as the board looked it up, once its proof is spent on the message's channel. */
|
|
5194
|
+
function spent(authorized, permission) {
|
|
5195
|
+
spend(authorized.proof, permission, authorized.message);
|
|
5196
|
+
return authorized.message;
|
|
5197
|
+
}
|
|
5198
|
+
async function writeEdit(ctx, input) {
|
|
5199
|
+
const message = spent(input.authorized, "post");
|
|
5200
|
+
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can edit a message");
|
|
5201
|
+
if (message.deleted) {
|
|
5202
|
+
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
5203
|
+
throw badRequest("message was deleted", "message_deleted");
|
|
5204
|
+
}
|
|
5205
|
+
return commitEdit(ctx, input, message);
|
|
5206
|
+
}
|
|
5207
|
+
async function commitEdit(ctx, input, message) {
|
|
5208
|
+
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5209
|
+
const seen = seenFor(input.identity, actors);
|
|
5210
|
+
const { text, found } = await withEmailMentions(input.text);
|
|
5211
|
+
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
5212
|
+
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? input.identity.actor : void 0, input.from != null, input.identity.principal.access.readsAll);
|
|
5213
|
+
const events = [
|
|
5214
|
+
...seen ? [seen] : [],
|
|
5215
|
+
...named,
|
|
5216
|
+
{
|
|
5217
|
+
type: "message.edited",
|
|
5218
|
+
payload: {
|
|
5219
|
+
id: message.id,
|
|
5220
|
+
thread: message.thread,
|
|
5221
|
+
text,
|
|
5222
|
+
mentions,
|
|
5223
|
+
by: input.identity.author,
|
|
5224
|
+
from: input.from ?? null
|
|
5225
|
+
}
|
|
4996
5226
|
}
|
|
4997
|
-
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
|
|
5003
|
-
|
|
5004
|
-
|
|
5227
|
+
];
|
|
5228
|
+
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
|
|
5229
|
+
return unknown.length && input.identity.principal.access.readable(message.channel) ? { unknownMentions: unknown } : {};
|
|
5230
|
+
}
|
|
5231
|
+
/** A message's links, replaced: a platform edit or unfurl changed what it links to. */
|
|
5232
|
+
async function writeLinks(ctx, input) {
|
|
5233
|
+
const message = spent(input.authorized, "post");
|
|
5234
|
+
if (message.deleted) return;
|
|
5235
|
+
await untilApplied(ctx, await ctx.session.append({
|
|
5236
|
+
type: "message.linked",
|
|
5237
|
+
payload: {
|
|
5238
|
+
id: message.id,
|
|
5239
|
+
thread: message.thread,
|
|
5240
|
+
links: input.links,
|
|
5241
|
+
by: input.identity.author,
|
|
5242
|
+
from: input.from
|
|
5005
5243
|
}
|
|
5006
|
-
|
|
5007
|
-
};
|
|
5244
|
+
}));
|
|
5008
5245
|
}
|
|
5009
|
-
|
|
5010
|
-
|
|
5011
|
-
|
|
5012
|
-
|
|
5013
|
-
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
const
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5246
|
+
async function writeDelete(ctx, input) {
|
|
5247
|
+
const message = spent(input.authorized, "post");
|
|
5248
|
+
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can delete a message");
|
|
5249
|
+
if (message.deleted) {
|
|
5250
|
+
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
5251
|
+
return;
|
|
5252
|
+
}
|
|
5253
|
+
const deleted = [{
|
|
5254
|
+
type: "message.deleted",
|
|
5255
|
+
payload: {
|
|
5256
|
+
id: message.id,
|
|
5257
|
+
thread: message.thread,
|
|
5258
|
+
by: input.identity.author,
|
|
5259
|
+
from: input.from ?? null
|
|
5260
|
+
}
|
|
5261
|
+
}];
|
|
5262
|
+
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...deleted) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), deleted));
|
|
5022
5263
|
}
|
|
5023
|
-
/**
|
|
5024
|
-
|
|
5025
|
-
const
|
|
5026
|
-
const
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
|
|
5032
|
-
|
|
5033
|
-
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
|
|
5037
|
-
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5264
|
+
/** An edit's or a delete's `revision`: no edit or delete since, as of the index the read reflects. */
|
|
5265
|
+
const revisionIs = (ctx, id, revision) => async () => {
|
|
5266
|
+
const position = await ctx.reads.tables.position();
|
|
5267
|
+
const message = (await ctx.reads.tables.messagesAt([id], position)).get(id);
|
|
5268
|
+
const now = message ? message.revision ?? message.id : null;
|
|
5269
|
+
if (now !== revision) throw new HttpError(409, "revision_conflict", message?.deleted ? `#${id} was deleted since revision ${revision}` : `#${id} was edited since revision ${revision}: it's at ${now}`);
|
|
5270
|
+
return position;
|
|
5271
|
+
};
|
|
5272
|
+
async function writeReaction(ctx, input) {
|
|
5273
|
+
const message = spent(input.authorized, "react");
|
|
5274
|
+
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
5275
|
+
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5276
|
+
const seen = seenFor(input.identity, actors);
|
|
5277
|
+
await untilApplied(ctx, await ctx.session.append(...seen ? [seen] : [], {
|
|
5278
|
+
type: input.remove ? "reaction.removed" : "reaction.added",
|
|
5279
|
+
payload: {
|
|
5280
|
+
id: message.id,
|
|
5281
|
+
thread: message.thread,
|
|
5282
|
+
emoji: input.emoji,
|
|
5283
|
+
by: input.identity.author,
|
|
5284
|
+
from: input.from ?? null
|
|
5285
|
+
}
|
|
5286
|
+
}));
|
|
5287
|
+
}
|
|
5288
|
+
async function writeLabels(ctx, input) {
|
|
5289
|
+
const message = spent(input.authorized, "label");
|
|
5290
|
+
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
5291
|
+
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5292
|
+
const seen = seenFor(input.identity, actors);
|
|
5293
|
+
const events = [...seen ? [seen] : [], {
|
|
5294
|
+
type: "labels.changed",
|
|
5295
|
+
payload: {
|
|
5296
|
+
id: message.id,
|
|
5297
|
+
thread: message.thread,
|
|
5298
|
+
set: input.set ?? {},
|
|
5299
|
+
unset: input.unset ?? [],
|
|
5300
|
+
by: input.identity.author
|
|
5301
|
+
}
|
|
5302
|
+
}];
|
|
5303
|
+
await untilApplied(ctx, input.if !== void 0 && Object.keys(input.if).length > 0 ? await appendWhile(ctx, labelsAre(ctx, message.id, input.if), events) : await ctx.session.append(...events));
|
|
5304
|
+
}
|
|
5305
|
+
/** A label write's `if`: each label is as it says, as of the index the read reflects. */
|
|
5306
|
+
const labelsAre = (ctx, id, expected) => async () => {
|
|
5307
|
+
const position = await ctx.reads.tables.position();
|
|
5308
|
+
const labels = (await ctx.reads.tables.messagesAt([id], position)).get(id)?.labels ?? {};
|
|
5309
|
+
for (const key of Object.keys(expected).sort()) {
|
|
5310
|
+
const now = own(labels, key);
|
|
5311
|
+
if (now === expected[key] || now === void 0 && expected[key] === null) continue;
|
|
5312
|
+
const wanted = expected[key];
|
|
5313
|
+
throw new HttpError(409, "label_conflict", wanted === null ? `${key} is set` : now === void 0 ? `${key} isn't set` : `${key} isn't ${wanted}`);
|
|
5041
5314
|
}
|
|
5042
|
-
|
|
5043
|
-
|
|
5044
|
-
|
|
5045
|
-
|
|
5046
|
-
|
|
5047
|
-
|
|
5315
|
+
return position;
|
|
5316
|
+
};
|
|
5317
|
+
/**
|
|
5318
|
+
* Syncs a message's thread with a target, resolved by the sync that delivers it. Attaching twice
|
|
5319
|
+
* is a no-op; a platform thread another board thread is synced with is a 409.
|
|
5320
|
+
*/
|
|
5321
|
+
async function writeAttach(ctx, input) {
|
|
5322
|
+
const message = spent(input.authorized, "sync");
|
|
5323
|
+
const { target, kind } = input.target;
|
|
5324
|
+
await ctx.reads.ensure();
|
|
5325
|
+
if ((await ctx.reads.tables.syncOf(message.thread))?.targets.includes(target)) return { attached: false };
|
|
5326
|
+
await unclaimed(ctx, input.target, message.thread, input.identity.principal.access);
|
|
5327
|
+
await untilApplied(ctx, await ctx.session.append({
|
|
5328
|
+
type: "thread.synced",
|
|
5329
|
+
id: await derivedId("board", message.thread, "sync", target),
|
|
5330
|
+
payload: {
|
|
5331
|
+
thread: message.thread,
|
|
5332
|
+
target,
|
|
5333
|
+
kind,
|
|
5334
|
+
cause: input.cause,
|
|
5335
|
+
by: input.identity.author
|
|
5336
|
+
}
|
|
5048
5337
|
}));
|
|
5049
|
-
return
|
|
5338
|
+
return { attached: true };
|
|
5050
5339
|
}
|
|
5051
5340
|
/**
|
|
5052
|
-
*
|
|
5053
|
-
*
|
|
5054
|
-
*
|
|
5341
|
+
* A channel made before anything posts to it, or the one that's there, made by a post or another
|
|
5342
|
+
* create, which `created: false` says. It needs `read` and `post` there, refused alike whether it's
|
|
5343
|
+
* there or not: the answer says whether it was, and shows what it holds.
|
|
5055
5344
|
*/
|
|
5056
|
-
async function
|
|
5057
|
-
const
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
const
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
const message = found.get(want);
|
|
5067
|
-
if (message) messages.byId[want] = message;
|
|
5345
|
+
async function writeChannel(ctx, input) {
|
|
5346
|
+
const { access } = input.identity.principal;
|
|
5347
|
+
authorize(access, "read", input.path);
|
|
5348
|
+
authorize(access, "post", input.path);
|
|
5349
|
+
const seen = seenFor(input.identity, (await ctx.session.state(actorsReducer)).state);
|
|
5350
|
+
const events = [...seen ? [seen] : [], {
|
|
5351
|
+
type: "channel.created",
|
|
5352
|
+
payload: {
|
|
5353
|
+
channel: input.path,
|
|
5354
|
+
by: input.identity.author
|
|
5068
5355
|
}
|
|
5356
|
+
}];
|
|
5357
|
+
const made = await whileHeadMoves(async () => {
|
|
5358
|
+
const { state, index } = await ctx.session.state(channelsReducer, { through: "latest" });
|
|
5359
|
+
const found = own(state, input.path);
|
|
5360
|
+
return found ? { found } : { rows: await appendIfLast(ctx.session, index, events) };
|
|
5361
|
+
});
|
|
5362
|
+
if ("found" in made) return {
|
|
5363
|
+
channel: made.found,
|
|
5364
|
+
created: false
|
|
5069
5365
|
};
|
|
5070
|
-
|
|
5071
|
-
else await load([id]);
|
|
5072
|
-
const re = event.type === "message.posted" ? event.payload.re : messages.byId[id]?.re ?? null;
|
|
5073
|
-
if (re !== null) await load([re]);
|
|
5074
|
-
}
|
|
5075
|
-
/** The message `event` concerns and its root, as they were just before it. */
|
|
5076
|
-
async function loadBefore(reads, event, signal) {
|
|
5077
|
-
const messages = {
|
|
5078
|
-
byId: {},
|
|
5079
|
-
replies: {}
|
|
5080
|
-
};
|
|
5081
|
-
await loadInto(reads, messages, /* @__PURE__ */ new Set(), event, signal);
|
|
5082
|
-
return messages;
|
|
5083
|
-
}
|
|
5084
|
-
/** Folds one event into `messages` and `actors`, and returns the message it concerns before and after. */
|
|
5085
|
-
function foldEvent(messages, actors, event) {
|
|
5086
|
-
const id = concernedMessageId(event);
|
|
5087
|
-
const before = id === null ? void 0 : structuredClone(messages.byId[id]);
|
|
5088
|
-
foldMessages(messages, event);
|
|
5089
|
-
foldActors(actors, event);
|
|
5090
|
-
return {
|
|
5091
|
-
id,
|
|
5092
|
-
before,
|
|
5093
|
-
after: id === null ? void 0 : messages.byId[id]
|
|
5094
|
-
};
|
|
5095
|
-
}
|
|
5096
|
-
/** An event as subscribers receive it, with its message as it is afterwards. */
|
|
5097
|
-
function eventView(event, after, actors, reader) {
|
|
5098
|
-
const by = event.payload.by?.actor;
|
|
5099
|
-
const actor = by ? own(actors.byId, by) : void 0;
|
|
5100
|
-
const { links } = event.payload;
|
|
5366
|
+
await untilApplied(ctx, made.rows);
|
|
5101
5367
|
return {
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
|
|
5108
|
-
|
|
5109
|
-
...actorView(actors, actor.id)
|
|
5110
|
-
} } : {}
|
|
5111
|
-
};
|
|
5112
|
-
}
|
|
5113
|
-
/** An event's payload as clients see it: the message IDs in it are refs. */
|
|
5114
|
-
function payloadView(payload, links) {
|
|
5115
|
-
const shown = { ...payload };
|
|
5116
|
-
for (const key of [
|
|
5117
|
-
"id",
|
|
5118
|
-
"re",
|
|
5119
|
-
"replyTo"
|
|
5120
|
-
]) if (typeof shown[key] === "number") shown[key] = ref(shown[key]);
|
|
5121
|
-
const schedule = shown.schedule;
|
|
5122
|
-
if (schedule) shown.schedule = {
|
|
5123
|
-
id: scheduleRef(schedule.id),
|
|
5124
|
-
n: schedule.n
|
|
5368
|
+
channel: {
|
|
5369
|
+
path: input.path,
|
|
5370
|
+
lastIndex: 0,
|
|
5371
|
+
messages: 0,
|
|
5372
|
+
threads: 0
|
|
5373
|
+
},
|
|
5374
|
+
created: true
|
|
5125
5375
|
};
|
|
5126
|
-
if (links) shown.links = links;
|
|
5127
|
-
return shown;
|
|
5128
5376
|
}
|
|
5377
|
+
/** The batch, only while `index` is still the session's last: A2's conditional append. */
|
|
5378
|
+
const appendIfLast = (session, index, events) => session.append.ifLastIndex(index, ...events);
|
|
5379
|
+
/** What A2 throws when the session's last index isn't the one a conditional append named. */
|
|
5380
|
+
const headMoved = (error) => error?.code === "LAST_INDEX_MISMATCH";
|
|
5381
|
+
//#endregion
|
|
5382
|
+
//#region src/server/trust.ts
|
|
5383
|
+
/** How long a token lives when its minter doesn't say, and at most: npm caps its write tokens at 90 days. */
|
|
5384
|
+
const TOKEN_DEFAULT_MS = 2592e6;
|
|
5385
|
+
/** How deep tokens minted with tokens go: each request walks the chain to its root. */
|
|
5386
|
+
const TOKEN_DEPTH_MAX = 8;
|
|
5129
5387
|
/**
|
|
5130
|
-
*
|
|
5131
|
-
*
|
|
5132
|
-
*
|
|
5133
|
-
*
|
|
5134
|
-
*
|
|
5135
|
-
*
|
|
5136
|
-
* It's the one choke point for `/events` (tail, wait, and poll): an event about
|
|
5137
|
-
* a message shows only where `access` reads its channel, and one about no
|
|
5138
|
-
* message (who's who, a thread's sync) only to a reader of every channel.
|
|
5388
|
+
* The grants a board starts with, as a team's board in Vercel's API does: g1, every person may do
|
|
5389
|
+
* everything (no team roles cap it here), g2, every project on the board's team, in every
|
|
5390
|
+
* environment, reads, posts, reacts, and labels everywhere, and g3, every app on the team, the
|
|
5391
|
+
* same. A local board has no apps, so g3 names no one here, but the defaults are the same
|
|
5392
|
+
* everywhere. Revoke or change them like any other.
|
|
5139
5393
|
*/
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
|
|
5157
|
-
|
|
5158
|
-
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
|
|
5167
|
-
|
|
5168
|
-
|
|
5169
|
-
|
|
5170
|
-
|
|
5171
|
-
|
|
5172
|
-
|
|
5173
|
-
|
|
5174
|
-
|
|
5175
|
-
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
const message = found.get(id);
|
|
5182
|
-
if (message) this.messages.byId[id] = message;
|
|
5183
|
-
}
|
|
5184
|
-
};
|
|
5185
|
-
await load([...ids].filter((id) => !this.loaded.has(id) && id <= index));
|
|
5186
|
-
const roots = Object.values(this.messages.byId).flatMap((message) => message.re === null ? [] : [message.re]);
|
|
5187
|
-
await load([...new Set(roots)].filter((id) => !this.loaded.has(id)));
|
|
5188
|
-
}
|
|
5189
|
-
async step(event, signal) {
|
|
5190
|
-
await loadInto(this.reads, this.messages, this.loaded, event, signal);
|
|
5191
|
-
const { id, before, after } = foldEvent(this.messages, this.actors, event);
|
|
5192
|
-
const message = after ?? before;
|
|
5193
|
-
const readable = id === null ? this.access.readsAll : message !== void 0 && this.access.readable(message.channel);
|
|
5194
|
-
const hidden = HIDDEN.has(event.type) && !this.all;
|
|
5195
|
-
if (!(readable && !hidden && (this.criteria ? this.match(before) || this.match(after) : id !== null || this.all))) return {
|
|
5196
|
-
index: event.index,
|
|
5197
|
-
view: null
|
|
5198
|
-
};
|
|
5199
|
-
await this.loadLinked([...after?.links ?? [], ...event.payload.links ?? []], event.index, signal);
|
|
5200
|
-
const reader = {
|
|
5201
|
-
access: this.access,
|
|
5202
|
-
channelOf: (message) => this.messages.byId[message]?.channel ?? this.linked.get(message)
|
|
5203
|
-
};
|
|
5204
|
-
return {
|
|
5205
|
-
index: event.index,
|
|
5206
|
-
view: eventView(event, after, this.actors, reader)
|
|
5207
|
-
};
|
|
5208
|
-
}
|
|
5209
|
-
/** Where the messages `links` point to live; a message never moves, so any version says. */
|
|
5210
|
-
async loadLinked(links, index, signal) {
|
|
5211
|
-
if (this.access.readsAll) return;
|
|
5212
|
-
const wanted = [...new Set(linkedIds(links))].filter((id) => !this.messages.byId[id] && !this.linked.has(id));
|
|
5213
|
-
if (wanted.length === 0) return;
|
|
5214
|
-
const found = await this.reads.messagesAt(wanted, index, signal);
|
|
5215
|
-
for (const id of wanted) this.linked.set(id, found.get(id)?.channel);
|
|
5394
|
+
const STARTING_GRANTS = {
|
|
5395
|
+
1: {
|
|
5396
|
+
id: 1,
|
|
5397
|
+
event: null,
|
|
5398
|
+
principals: [{ kind: "all-users" }],
|
|
5399
|
+
can: { "*": "all" },
|
|
5400
|
+
by: null,
|
|
5401
|
+
at: null
|
|
5402
|
+
},
|
|
5403
|
+
2: {
|
|
5404
|
+
id: 2,
|
|
5405
|
+
event: null,
|
|
5406
|
+
principals: [{
|
|
5407
|
+
kind: "all-projects",
|
|
5408
|
+
environments: [
|
|
5409
|
+
"production",
|
|
5410
|
+
"preview",
|
|
5411
|
+
"development"
|
|
5412
|
+
]
|
|
5413
|
+
}],
|
|
5414
|
+
can: { "*": [
|
|
5415
|
+
"read",
|
|
5416
|
+
"post",
|
|
5417
|
+
"react",
|
|
5418
|
+
"label"
|
|
5419
|
+
] },
|
|
5420
|
+
by: null,
|
|
5421
|
+
at: null
|
|
5422
|
+
},
|
|
5423
|
+
3: {
|
|
5424
|
+
id: 3,
|
|
5425
|
+
event: null,
|
|
5426
|
+
principals: [{ kind: "all-apps" }],
|
|
5427
|
+
can: { "*": [
|
|
5428
|
+
"read",
|
|
5429
|
+
"post",
|
|
5430
|
+
"react",
|
|
5431
|
+
"label"
|
|
5432
|
+
] },
|
|
5433
|
+
by: null,
|
|
5434
|
+
at: null
|
|
5216
5435
|
}
|
|
5217
5436
|
};
|
|
5218
|
-
/**
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
|
|
5437
|
+
/** The access session before its first event: the grants every board starts with, and no tokens. */
|
|
5438
|
+
const startingAccess = () => ({
|
|
5439
|
+
grants: structuredClone(STARTING_GRANTS),
|
|
5440
|
+
nextGrant: 4,
|
|
5441
|
+
tokens: {},
|
|
5442
|
+
hashes: {},
|
|
5443
|
+
expiring: {},
|
|
5444
|
+
pruned: null
|
|
5445
|
+
});
|
|
5446
|
+
const DAY_MS = 864e5;
|
|
5447
|
+
function dropToken(state, id) {
|
|
5448
|
+
const row = state.tokens[id];
|
|
5449
|
+
if (!row) return;
|
|
5450
|
+
delete state.hashes[row.hash];
|
|
5451
|
+
delete state.tokens[id];
|
|
5232
5452
|
}
|
|
5233
|
-
/**
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5453
|
+
/** Whether token `id` is token `ancestor`, or was minted with it at any depth. */
|
|
5454
|
+
function mintedWith(state, id, ancestor) {
|
|
5455
|
+
let at = id;
|
|
5456
|
+
for (let depth = 0; at !== null && depth <= TOKEN_DEPTH_MAX; depth++) {
|
|
5457
|
+
if (at === ancestor) return true;
|
|
5458
|
+
at = state.tokens[at]?.parent ?? null;
|
|
5459
|
+
}
|
|
5460
|
+
return false;
|
|
5237
5461
|
}
|
|
5238
|
-
const PAGE = 200;
|
|
5239
5462
|
/**
|
|
5240
|
-
*
|
|
5241
|
-
*
|
|
5242
|
-
*
|
|
5463
|
+
* Whether `identity` may see and revoke token `row`: anyone's with `manage` in every channel. A
|
|
5464
|
+
* token acts as its minter, so its principal alone would hand it every token its minter has: with
|
|
5465
|
+
* a token, it's that token and those minted with it; without one, those its principal minted.
|
|
5243
5466
|
*/
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
|
|
5257
|
-
|
|
5467
|
+
function manages(state, { principal }, row) {
|
|
5468
|
+
if (principal.access.everywhere("manage")) return true;
|
|
5469
|
+
if (row.minter.id !== principal.id) return false;
|
|
5470
|
+
if (principal.token === void 0) return true;
|
|
5471
|
+
const held = indexOf(principal.token, "t");
|
|
5472
|
+
return held !== null && mintedWith(state, row.id, held);
|
|
5473
|
+
}
|
|
5474
|
+
/**
|
|
5475
|
+
* The access session's fold. It prunes by the events' own times, so every instance folds the same
|
|
5476
|
+
* state, and each event costs a day's expired tokens at most. A child whose parent is gone counts
|
|
5477
|
+
* as dead (`liveIn`), and lives no longer than its parent, so pruning never brings one back.
|
|
5478
|
+
*/
|
|
5479
|
+
function foldAccess(state, event) {
|
|
5480
|
+
const at = new Date(event.createdAt).getTime();
|
|
5481
|
+
const day = Math.floor(at / DAY_MS);
|
|
5482
|
+
if (state.pruned === null) state.pruned = day;
|
|
5483
|
+
for (; state.pruned < day; state.pruned++) {
|
|
5484
|
+
for (const id of state.expiring[state.pruned] ?? []) dropToken(state, id);
|
|
5485
|
+
delete state.expiring[state.pruned];
|
|
5258
5486
|
}
|
|
5259
|
-
|
|
5260
|
-
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
|
|
5270
|
-
|
|
5271
|
-
|
|
5487
|
+
switch (event.type) {
|
|
5488
|
+
case "grant.set":
|
|
5489
|
+
case "grant.revoked": break;
|
|
5490
|
+
case "grant.created": {
|
|
5491
|
+
const { principals, can, by } = event.payload;
|
|
5492
|
+
const id = state.nextGrant++;
|
|
5493
|
+
state.grants[id] = {
|
|
5494
|
+
id,
|
|
5495
|
+
event: event.index,
|
|
5496
|
+
principals,
|
|
5497
|
+
can,
|
|
5498
|
+
by,
|
|
5499
|
+
at
|
|
5272
5500
|
};
|
|
5273
|
-
|
|
5274
|
-
cursor = item.index;
|
|
5275
|
-
if (item.view) {
|
|
5276
|
-
events.push(item.view);
|
|
5277
|
-
return {
|
|
5278
|
-
events,
|
|
5279
|
-
cursor
|
|
5280
|
-
};
|
|
5281
|
-
}
|
|
5501
|
+
break;
|
|
5282
5502
|
}
|
|
5283
|
-
|
|
5284
|
-
|
|
5503
|
+
case "grant.updated": {
|
|
5504
|
+
const { id, principals, can, by } = event.payload;
|
|
5505
|
+
const row = state.grants[id];
|
|
5506
|
+
if (row) Object.assign(row, {
|
|
5507
|
+
principals,
|
|
5508
|
+
can,
|
|
5509
|
+
by,
|
|
5510
|
+
at
|
|
5511
|
+
});
|
|
5512
|
+
break;
|
|
5513
|
+
}
|
|
5514
|
+
case "grant.deleted":
|
|
5515
|
+
delete state.grants[event.payload.id];
|
|
5516
|
+
break;
|
|
5517
|
+
case "token.minted": {
|
|
5518
|
+
const { payload } = event;
|
|
5519
|
+
if (state.hashes[payload.hash] !== void 0) break;
|
|
5520
|
+
state.tokens[event.index] = {
|
|
5521
|
+
id: event.index,
|
|
5522
|
+
...payload,
|
|
5523
|
+
minter: payload.minter,
|
|
5524
|
+
at
|
|
5525
|
+
};
|
|
5526
|
+
state.hashes[payload.hash] = event.index;
|
|
5527
|
+
(state.expiring[Math.floor(payload.expiresAt / DAY_MS)] ??= []).push(event.index);
|
|
5528
|
+
break;
|
|
5529
|
+
}
|
|
5530
|
+
case "token.revoked": dropToken(state, event.payload.id);
|
|
5285
5531
|
}
|
|
5532
|
+
return state;
|
|
5286
5533
|
}
|
|
5287
|
-
|
|
5288
|
-
|
|
5289
|
-
|
|
5290
|
-
|
|
5291
|
-
|
|
5292
|
-
|
|
5293
|
-
|
|
5294
|
-
|
|
5295
|
-
|
|
5296
|
-
}).
|
|
5297
|
-
|
|
5298
|
-
await tables.apply(ctx.event);
|
|
5299
|
-
});
|
|
5534
|
+
const accessReducer = reducer({
|
|
5535
|
+
contract: accessContract,
|
|
5536
|
+
name: "board.access.v2",
|
|
5537
|
+
initialState: startingAccess()
|
|
5538
|
+
}).fold(foldAccess);
|
|
5539
|
+
const grantId = (id) => `g${id}`;
|
|
5540
|
+
const tokenId = (id) => `t${id}`;
|
|
5541
|
+
/** The index an ID names: `g12` or `t12` for 12. Null for one that names none. */
|
|
5542
|
+
function indexOf(id, prefix) {
|
|
5543
|
+
const found = new RegExp(`^${prefix}([1-9]\\d{0,15})$`).exec(id);
|
|
5544
|
+
return found ? Number(found[1]) : null;
|
|
5300
5545
|
}
|
|
5301
|
-
/**
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5307
|
-
|
|
5308
|
-
* The first list read on an instance starts the tables catching up, and doesn't wait: after a deploy
|
|
5309
|
-
* that adds them, or on a quiet board, nothing else may have yet.
|
|
5310
|
-
*/
|
|
5311
|
-
let catching = null;
|
|
5312
|
-
/**
|
|
5313
|
-
* The reader of views whose links point to the board messages `linked`, looked up only for a
|
|
5314
|
-
* reader that can't read every channel. A linked message is older than the one linking it, so
|
|
5315
|
-
* the tables have it.
|
|
5316
|
-
*/
|
|
5317
|
-
async function readerOf(access, linked) {
|
|
5318
|
-
if (access.readsAll) return {
|
|
5319
|
-
access,
|
|
5320
|
-
channelOf: () => void 0
|
|
5546
|
+
/** A principal as views show it: the IDs, and the names the board knows, which on a local board are none. */
|
|
5547
|
+
function principalView(principal) {
|
|
5548
|
+
switch (principal.kind) {
|
|
5549
|
+
case "user": return {
|
|
5550
|
+
kind: "user",
|
|
5551
|
+
userId: principal.userId,
|
|
5552
|
+
email: principal.email ?? null
|
|
5321
5553
|
};
|
|
5322
|
-
|
|
5323
|
-
|
|
5324
|
-
|
|
5325
|
-
|
|
5326
|
-
|
|
5554
|
+
case "project": return {
|
|
5555
|
+
kind: "project",
|
|
5556
|
+
projectId: principal.projectId,
|
|
5557
|
+
name: principal.name ?? null,
|
|
5558
|
+
environments: [...principal.environments],
|
|
5559
|
+
teamId: principal.teamId ?? null
|
|
5327
5560
|
};
|
|
5561
|
+
case "github": return {
|
|
5562
|
+
...principal,
|
|
5563
|
+
repositoryId: principal.repositoryId ?? null
|
|
5564
|
+
};
|
|
5565
|
+
case "oidc": return {
|
|
5566
|
+
kind: "oidc",
|
|
5567
|
+
issuer: principal.issuer,
|
|
5568
|
+
claims: Object.fromEntries(Object.entries(principal.claims).map(([name, value]) => [name, typeof value === "string" ? value : [...value]]))
|
|
5569
|
+
};
|
|
5570
|
+
case "all-projects": return {
|
|
5571
|
+
kind: "all-projects",
|
|
5572
|
+
environments: [...principal.environments]
|
|
5573
|
+
};
|
|
5574
|
+
case "app": return {
|
|
5575
|
+
kind: "app",
|
|
5576
|
+
clientId: principal.clientId,
|
|
5577
|
+
name: principal.name ?? null
|
|
5578
|
+
};
|
|
5579
|
+
default: return { kind: principal.kind };
|
|
5328
5580
|
}
|
|
5329
|
-
function catchUp() {
|
|
5330
|
-
if (catching) return;
|
|
5331
|
-
catching = session.consume(projection).catch(() => {
|
|
5332
|
-
catching = null;
|
|
5333
|
-
});
|
|
5334
|
-
waitUntil(catching);
|
|
5335
|
-
}
|
|
5336
|
-
/**
|
|
5337
|
-
* The tables caught up with the whole log once on this instance. Until then, a read by index waits
|
|
5338
|
-
* for all of it: tables rebuilt from the log can be far behind, and a message's later events (an
|
|
5339
|
-
* edit, a reaction, a reply) come after its own index. Once caught up, each write applies as it lands.
|
|
5340
|
-
*/
|
|
5341
|
-
let whole = null;
|
|
5342
|
-
function caughtUp() {
|
|
5343
|
-
whole ??= session.consume(projection).then(() => void 0, (error) => {
|
|
5344
|
-
whole = null;
|
|
5345
|
-
throw error;
|
|
5346
|
-
});
|
|
5347
|
-
return whole;
|
|
5348
|
-
}
|
|
5349
|
-
/** `promise`, unless `signal` aborts first: the caller stops waiting, and what it waits for keeps going. */
|
|
5350
|
-
function untilAborted(promise, signal) {
|
|
5351
|
-
if (!signal) return promise;
|
|
5352
|
-
if (signal.aborted) return Promise.reject(signal.reason);
|
|
5353
|
-
return new Promise((resolve, reject) => {
|
|
5354
|
-
const abort = () => reject(signal.reason);
|
|
5355
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
5356
|
-
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
5357
|
-
});
|
|
5358
|
-
}
|
|
5359
|
-
/** Waits until the tables have applied `index`, or the whole log when it's omitted. */
|
|
5360
|
-
async function ensure(index, signal) {
|
|
5361
|
-
if (index !== void 0) await untilAborted(caughtUp(), signal);
|
|
5362
|
-
if (index !== void 0 && await tables.position() >= index) return;
|
|
5363
|
-
await session.consume(projection, {
|
|
5364
|
-
...index !== void 0 ? { through: index } : {},
|
|
5365
|
-
...signal ? { signal } : {}
|
|
5366
|
-
});
|
|
5367
|
-
}
|
|
5368
|
-
return {
|
|
5369
|
-
tables,
|
|
5370
|
-
ensure,
|
|
5371
|
-
position: () => tables.position(),
|
|
5372
|
-
async message(id, signal) {
|
|
5373
|
-
await ensure(id, signal);
|
|
5374
|
-
return tables.message(id);
|
|
5375
|
-
},
|
|
5376
|
-
/** A thread's root and replies; `cursor` is the index the tables had applied before reading it. */
|
|
5377
|
-
async thread(root, signal) {
|
|
5378
|
-
await ensure(root, signal);
|
|
5379
|
-
const cursor = await tables.position();
|
|
5380
|
-
return {
|
|
5381
|
-
messages: await tables.thread(root),
|
|
5382
|
-
cursor
|
|
5383
|
-
};
|
|
5384
|
-
},
|
|
5385
|
-
async messagesAt(ids, index, signal) {
|
|
5386
|
-
await ensure(index, signal);
|
|
5387
|
-
return tables.messagesAt(ids, index);
|
|
5388
|
-
},
|
|
5389
|
-
/** By event ID, as of the whole log: an ID doesn't say how far to wait. */
|
|
5390
|
-
async byEventId(eventId, signal) {
|
|
5391
|
-
await ensure(void 0, signal);
|
|
5392
|
-
return tables.byEventId(eventId);
|
|
5393
|
-
},
|
|
5394
|
-
/** The reader of views of `messages`: what a link shows depends on where the message it points to lives. */
|
|
5395
|
-
reader: (access, messages) => readerOf(access, [...messages].flatMap((message) => linkedIds(message.links))),
|
|
5396
|
-
readerOf,
|
|
5397
|
-
async messages(filter, page) {
|
|
5398
|
-
catchUp();
|
|
5399
|
-
if (filter.channels?.length === 0) return {
|
|
5400
|
-
messages: [],
|
|
5401
|
-
position: await tables.position()
|
|
5402
|
-
};
|
|
5403
|
-
return tables.messages(filter, page);
|
|
5404
|
-
},
|
|
5405
|
-
async threads(filter, page) {
|
|
5406
|
-
catchUp();
|
|
5407
|
-
if (filter.channels?.length === 0) return {
|
|
5408
|
-
threads: [],
|
|
5409
|
-
position: await tables.position()
|
|
5410
|
-
};
|
|
5411
|
-
return tables.threads(filter, page);
|
|
5412
|
-
}
|
|
5413
|
-
};
|
|
5414
5581
|
}
|
|
5415
|
-
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5423
|
-
|
|
5424
|
-
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
5434
|
-
|
|
5582
|
+
const grantView = (row) => ({
|
|
5583
|
+
id: grantId(row.id),
|
|
5584
|
+
principals: row.principals.map(principalView),
|
|
5585
|
+
can: Object.fromEntries(Object.entries(row.can).map(([pattern, grant]) => [pattern, grant === "all" ? "all" : [...grant]])),
|
|
5586
|
+
capped: false,
|
|
5587
|
+
by: row.by,
|
|
5588
|
+
at: row.at === null ? null : new Date(row.at).toISOString()
|
|
5589
|
+
});
|
|
5590
|
+
const storedGrant = (row) => ({
|
|
5591
|
+
id: grantId(row.id),
|
|
5592
|
+
principals: row.principals,
|
|
5593
|
+
can: row.can
|
|
5594
|
+
});
|
|
5595
|
+
/** A token as the protocol shows it, with `can` what it may do now (`accessNow`'s, for its minter). */
|
|
5596
|
+
const tokenView = (row, can) => ({
|
|
5597
|
+
id: tokenId(row.id),
|
|
5598
|
+
name: row.name,
|
|
5599
|
+
can: can === null ? {} : can.summary(),
|
|
5600
|
+
profile: row.profile,
|
|
5601
|
+
session: row.session,
|
|
5602
|
+
by: row.by,
|
|
5603
|
+
at: new Date(row.at).toISOString(),
|
|
5604
|
+
expiresAt: new Date(row.expiresAt).toISOString(),
|
|
5605
|
+
parent: row.parent === null ? null : tokenId(row.parent)
|
|
5606
|
+
});
|
|
5607
|
+
/** A new token's secret: the prefix and 32 random bytes, base64url. */
|
|
5608
|
+
function newSecret() {
|
|
5609
|
+
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
|
|
5610
|
+
return `${BOARD_TOKEN_PREFIX}${btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
|
|
5611
|
+
}
|
|
5612
|
+
/**
|
|
5613
|
+
* The principal an explain query names, as a token of its would make it: a person by user ID, a
|
|
5614
|
+
* project's deployment in one environment (production unless it says) on the board's team, a
|
|
5615
|
+
* repository's run with what it says of its workflow, branch (main unless it says), and event, or an issuer's token with
|
|
5616
|
+
* its claims. A board that verifies tokens itself looks no names up, so a name is a 400.
|
|
5617
|
+
*/
|
|
5618
|
+
function principalNamed(query, team) {
|
|
5619
|
+
if (query.user !== void 0) {
|
|
5620
|
+
if (query.user.includes("@")) throw badRequest(`this board can't look up ${query.user}: it verifies tokens itself, so name the user by ID`);
|
|
5621
|
+
return {
|
|
5622
|
+
id: `vercel:user:${query.user}`,
|
|
5623
|
+
kind: "person",
|
|
5624
|
+
handle: query.user
|
|
5625
|
+
};
|
|
5626
|
+
}
|
|
5627
|
+
if (query.project !== void 0) {
|
|
5628
|
+
if (!/^prj_[A-Za-z0-9]+$/.test(query.project)) throw badRequest(`this board can't look up the project ${query.project}: it verifies tokens itself, so name it by ID, prj_…`);
|
|
5629
|
+
const environment = query.environment ?? "production";
|
|
5630
|
+
const claims = {
|
|
5631
|
+
project_id: query.project,
|
|
5632
|
+
environment,
|
|
5633
|
+
...team !== null ? { owner_id: team } : {}
|
|
5634
|
+
};
|
|
5635
|
+
return {
|
|
5636
|
+
id: `vercel:project:${query.project}:${environment}`,
|
|
5435
5637
|
kind: "deployment",
|
|
5436
|
-
handle,
|
|
5437
|
-
|
|
5438
|
-
|
|
5638
|
+
handle: query.project,
|
|
5639
|
+
facts: {
|
|
5640
|
+
issuer: "vercel",
|
|
5641
|
+
iss: "",
|
|
5642
|
+
claims,
|
|
5643
|
+
...team !== null ? { team } : {}
|
|
5644
|
+
}
|
|
5645
|
+
};
|
|
5646
|
+
}
|
|
5647
|
+
if (query.github !== void 0) {
|
|
5648
|
+
const repository = query.github;
|
|
5649
|
+
const claims = { repository };
|
|
5650
|
+
const branch = query.branch ?? "main";
|
|
5651
|
+
if (query.workflow !== void 0) claims.workflow_ref = `${repository}/${workflowPath(query.workflow)}@refs/heads/${branch}`;
|
|
5652
|
+
claims.ref = `refs/heads/${branch}`;
|
|
5653
|
+
if (query.event !== void 0) claims.event_name = query.event;
|
|
5654
|
+
return {
|
|
5655
|
+
id: `github:repo:${repository}`,
|
|
5656
|
+
kind: "workflow",
|
|
5657
|
+
handle: repository,
|
|
5658
|
+
facts: {
|
|
5659
|
+
issuer: "github",
|
|
5660
|
+
iss: GITHUB_ISSUER,
|
|
5661
|
+
claims
|
|
5662
|
+
}
|
|
5663
|
+
};
|
|
5664
|
+
}
|
|
5665
|
+
const iss = query.oidc;
|
|
5666
|
+
const claims = {};
|
|
5667
|
+
for (const pair of query.claim ?? []) {
|
|
5668
|
+
const at = pair.indexOf("=");
|
|
5669
|
+
if (at <= 0) throw badRequest(`a claim is name=value, and ${pair} isn't one`);
|
|
5670
|
+
claims[pair.slice(0, at)] = pair.slice(at + 1);
|
|
5671
|
+
}
|
|
5672
|
+
let name;
|
|
5673
|
+
try {
|
|
5674
|
+
name = issuerName(iss);
|
|
5675
|
+
} catch {
|
|
5676
|
+
throw badRequest(`an oidc issuer is an https URL, got ${iss}`);
|
|
5677
|
+
}
|
|
5678
|
+
return {
|
|
5679
|
+
id: `oidc:${name}:${claims.sub ?? "explain"}`,
|
|
5680
|
+
kind: "workflow",
|
|
5681
|
+
handle: claims.sub ?? "oidc",
|
|
5682
|
+
facts: {
|
|
5683
|
+
issuer: "oidc",
|
|
5684
|
+
iss,
|
|
5685
|
+
claims
|
|
5439
5686
|
}
|
|
5440
5687
|
};
|
|
5441
5688
|
}
|
|
5442
5689
|
/**
|
|
5443
|
-
*
|
|
5444
|
-
*
|
|
5445
|
-
*
|
|
5446
|
-
*
|
|
5690
|
+
* Whether `principal` is the board's owner: its local user, the one a local issuer (`vb serve`'s)
|
|
5691
|
+
* mints a token for. A host's verifier can return any ID, `local:user:` ones included, so what it
|
|
5692
|
+
* made is never the owner. Everyone else, a person on the team included, changes grants as
|
|
5693
|
+
* `manage` lets them, so a grant on people holds against people.
|
|
5447
5694
|
*/
|
|
5448
|
-
|
|
5449
|
-
|
|
5450
|
-
|
|
5695
|
+
const isOwner = (principal) => principal.kind === "person" && principal.id.startsWith("local:user:") && principal.facts?.issuer !== "host";
|
|
5696
|
+
/** Whether `identity` may list the grants: `manage` at `*`, or the owner, as far as its token's scope allows. */
|
|
5697
|
+
function lists({ principal }) {
|
|
5698
|
+
if (principal.access.at("manage", "*")) return true;
|
|
5699
|
+
return isOwner(principal) && (principal.scope === void 0 || compileAccess(parseScope(principal.scope)).at("manage", "*"));
|
|
5700
|
+
}
|
|
5701
|
+
/** A 403 unless `identity` may list the grants. */
|
|
5702
|
+
function mayList(identity, what) {
|
|
5703
|
+
if (!lists(identity)) throw forbidden$1(`this token can't ${what}: it needs manage at *`);
|
|
5704
|
+
}
|
|
5705
|
+
/** `grants` with no `everyone` in them: what a caller's own limits are, its role, its grants and its groups', and its token. */
|
|
5706
|
+
const withoutEveryone = (grants) => grants.flatMap((grant) => {
|
|
5707
|
+
const principals = grant.principals.filter((principal) => principal.kind !== "everyone");
|
|
5708
|
+
return principals.length === 0 ? [] : [{
|
|
5709
|
+
...grant,
|
|
5710
|
+
principals
|
|
5711
|
+
}];
|
|
5712
|
+
});
|
|
5713
|
+
/**
|
|
5714
|
+
* What the caller may do on `grants`, the snapshot its write appends to (`caller`), and by its own
|
|
5715
|
+
* limits alone (`own`): null for an owner no token narrows. A 403 when it may do nothing.
|
|
5716
|
+
*/
|
|
5717
|
+
async function changerAccess({ principal }, grants, accessIn) {
|
|
5718
|
+
if (isOwner(principal)) {
|
|
5719
|
+
if (principal.scope === void 0) return null;
|
|
5720
|
+
const scoped = compileAccess(parseScope(principal.scope));
|
|
5721
|
+
return {
|
|
5722
|
+
caller: scoped,
|
|
5723
|
+
own: scoped
|
|
5724
|
+
};
|
|
5725
|
+
}
|
|
5726
|
+
const [caller, own] = await Promise.all([accessIn(principal, grants), accessIn(principal, withoutEveryone(grants))]);
|
|
5727
|
+
if (caller === null || own === null) throw forbidden$1("this token can't change grants: it may do nothing on this board");
|
|
5728
|
+
return {
|
|
5729
|
+
caller,
|
|
5730
|
+
own
|
|
5731
|
+
};
|
|
5451
5732
|
}
|
|
5452
|
-
/**
|
|
5453
|
-
|
|
5454
|
-
|
|
5455
|
-
|
|
5456
|
-
|
|
5457
|
-
|
|
5733
|
+
/**
|
|
5734
|
+
* A 403 unless `identity` may change grants so, on `before`, the grants the write appends to, and
|
|
5735
|
+
* `after`, as they'd be: `checkGrantChange`'s rule, which Vercel's API runs too. `changed` is a
|
|
5736
|
+
* grant made or widened, `revoked` one revoked, removed from, or updated, as it was. A refusal that
|
|
5737
|
+
* involves a stored grant names its patterns only to whoever may list the grants.
|
|
5738
|
+
*/
|
|
5739
|
+
async function mayGrant(identity, change, before, after, accessIn, what = "this grant") {
|
|
5740
|
+
const access = await changerAccess(identity, before, accessIn);
|
|
5741
|
+
if (access === null) return;
|
|
5742
|
+
const refused = checkGrantChange({
|
|
5743
|
+
...access,
|
|
5744
|
+
after,
|
|
5745
|
+
...change
|
|
5746
|
+
});
|
|
5747
|
+
if (refused?.reason === "reach") {
|
|
5748
|
+
if (change.revoked && !lists(identity)) throw forbidden$1(`this token can't ${what}: it needs manage wherever that grant reaches`);
|
|
5749
|
+
throw forbidden$1(`${change.revoked ? `this token can't ${what}: it` : what} reaches ${refused.pattern}, where you can't manage grants`);
|
|
5458
5750
|
}
|
|
5459
|
-
};
|
|
5460
|
-
|
|
5751
|
+
if (refused) throw forbidden$1(`you can't let anyone in: everyone gets ${refused.permission} in ${refused.pattern}, which you can't`);
|
|
5752
|
+
}
|
|
5753
|
+
/** An oidc principal: naming one makes the board fetch its issuer's keys, so it takes manage everywhere. */
|
|
5754
|
+
const namesIssuer = (principals) => principals.some((principal) => principal.kind === "oidc");
|
|
5461
5755
|
/**
|
|
5462
|
-
*
|
|
5463
|
-
*
|
|
5464
|
-
*
|
|
5756
|
+
* The event that makes `input`'s change to a grant in `state`, or why it can't: manage at its
|
|
5757
|
+
* patterns, and to add principals or set `can`, what making it would take, and manage everywhere to
|
|
5758
|
+
* name an oidc issuer. A removal goes by who a principal is; an add joins one the grant names
|
|
5759
|
+
* already. `issuers` are the ones the board's rules trust.
|
|
5465
5760
|
*/
|
|
5466
|
-
async function
|
|
5467
|
-
const
|
|
5468
|
-
|
|
5761
|
+
async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team) {
|
|
5762
|
+
const index = indexOf(id, "g");
|
|
5763
|
+
const row = index === null ? void 0 : state.grants[index];
|
|
5764
|
+
if (!row) {
|
|
5765
|
+
mayList(identity, "update grants");
|
|
5766
|
+
throw notFound(`grant not found: ${id}`, "grant_not_found");
|
|
5767
|
+
}
|
|
5768
|
+
const before = Object.values(state.grants).map(storedGrant);
|
|
5769
|
+
await mayGrant(identity, { revoked: row }, before, before.filter((other) => other.id !== storedGrant(row).id), accessIn, `update ${id}`);
|
|
5770
|
+
const others = grantIssuers(Object.values(state.grants).filter((other) => other.id !== row.id).map(storedGrant));
|
|
5771
|
+
let principals = [...row.principals];
|
|
5772
|
+
for (const input of remove ?? []) {
|
|
5773
|
+
const removal = checkPrincipal(input, [...issuers, ...others], true);
|
|
5774
|
+
const kept = principals.filter((principal) => !removes(removal, principal));
|
|
5775
|
+
if (kept.length === principals.length) throw badRequest(`${id} doesn't name that ${removal.kind} principal`, "not_in_grant");
|
|
5776
|
+
principals = kept;
|
|
5777
|
+
}
|
|
5778
|
+
for (const input of add ?? []) {
|
|
5779
|
+
const added = checkPrincipal(input, [
|
|
5780
|
+
...issuers,
|
|
5781
|
+
...others,
|
|
5782
|
+
...grantIssuers([{ principals }])
|
|
5783
|
+
], false, team);
|
|
5784
|
+
const at = principals.findIndex((principal) => joined(added, principal) !== null);
|
|
5785
|
+
if (at === -1) principals.push(added);
|
|
5786
|
+
else principals[at] = joined(added, principals[at]);
|
|
5787
|
+
}
|
|
5788
|
+
if (principals.length === 0) throw badRequest(`that leaves ${id} naming no one: revoke it instead`, "grant_empty");
|
|
5789
|
+
if (principals.length > 32) throw badRequest("a grant names at most 32 principals", "invalid_grant");
|
|
5790
|
+
const next = can === void 0 ? row.can : checkCan(can);
|
|
5791
|
+
const after = [...Object.values(state.grants).filter((other) => other.id !== row.id), {
|
|
5792
|
+
principals,
|
|
5793
|
+
can: next
|
|
5794
|
+
}];
|
|
5795
|
+
await mayGrant(identity, {
|
|
5796
|
+
revoked: row,
|
|
5797
|
+
...add !== void 0 || can !== void 0 ? { changed: { can: next } } : {}
|
|
5798
|
+
}, before, after, accessIn, `update ${id}`);
|
|
5799
|
+
if (namesIssuer(principals.filter((principal) => !row.principals.includes(principal)))) await mayGrant(identity, { changed: { can: { "*": "all" } } }, before, after, accessIn, "naming an oidc issuer");
|
|
5469
5800
|
return {
|
|
5470
|
-
|
|
5471
|
-
|
|
5801
|
+
type: "grant.updated",
|
|
5802
|
+
payload: {
|
|
5803
|
+
id: row.id,
|
|
5804
|
+
principals,
|
|
5805
|
+
can: next,
|
|
5806
|
+
by: identity.actor.id
|
|
5807
|
+
}
|
|
5472
5808
|
};
|
|
5473
5809
|
}
|
|
5474
5810
|
/**
|
|
5475
|
-
*
|
|
5476
|
-
*
|
|
5477
|
-
*
|
|
5478
|
-
* reads (a repo's workflows share one) doesn't reach that caller's messages.
|
|
5479
|
-
* A board token that pins a profile owns only what was written as it (`wroteAs`).
|
|
5480
|
-
* Someone else's answers 404 where you can't read it, and 403 where you can.
|
|
5811
|
+
* The board's grants and tokens, in session `access` of its log: what a local board answers for them, and
|
|
5812
|
+
* what board() checks requests against. `accessNow`: what a principal may do now, under board()'s
|
|
5813
|
+
* defaults and the grants, which a token's listing shows.
|
|
5481
5814
|
*/
|
|
5482
|
-
|
|
5483
|
-
const
|
|
5484
|
-
const
|
|
5485
|
-
|
|
5486
|
-
|
|
5487
|
-
|
|
5488
|
-
|
|
5489
|
-
|
|
5815
|
+
function createTrust(options) {
|
|
5816
|
+
const accessIn = (principal, grants) => options.accessNow(principal, grants);
|
|
5817
|
+
const session = createServer({
|
|
5818
|
+
contract: accessContract,
|
|
5819
|
+
store: options.store
|
|
5820
|
+
}).session(ACCESS_SESSION);
|
|
5821
|
+
const read = async () => (await session.state(accessReducer)).state;
|
|
5822
|
+
/** The grants and tokens as they are now, and the index a conditional write holds them at. */
|
|
5823
|
+
const latest = () => session.state(accessReducer, { through: "latest" });
|
|
5824
|
+
/**
|
|
5825
|
+
* What each of `rows` may do now: its minter's access, narrowed by its scope. A minter's is worked
|
|
5826
|
+
* out once, however many tokens it has.
|
|
5827
|
+
*/
|
|
5828
|
+
async function viewsOf(rows) {
|
|
5829
|
+
const minters = /* @__PURE__ */ new Map();
|
|
5830
|
+
return Promise.all(rows.map(async (row) => {
|
|
5831
|
+
const { scope, ...minter } = row.minter;
|
|
5832
|
+
const key = JSON.stringify(minter);
|
|
5833
|
+
let access = minters.get(key);
|
|
5834
|
+
if (!access) minters.set(key, access = options.accessNow(minter));
|
|
5835
|
+
const now = await access;
|
|
5836
|
+
return tokenView(row, now === null || scope === void 0 ? now : now.narrow(parseScope(scope)));
|
|
5837
|
+
}));
|
|
5838
|
+
}
|
|
5839
|
+
/** Whether token `id` and every token it was minted with are live now. */
|
|
5840
|
+
function liveIn(state, id) {
|
|
5841
|
+
let at = id;
|
|
5842
|
+
for (let depth = 0; at !== null; depth++) {
|
|
5843
|
+
const row = state.tokens[at];
|
|
5844
|
+
if (!row || row.expiresAt <= Date.now() || depth > TOKEN_DEPTH_MAX) return false;
|
|
5845
|
+
at = row.parent;
|
|
5846
|
+
}
|
|
5847
|
+
return true;
|
|
5490
5848
|
}
|
|
5491
5849
|
return {
|
|
5492
|
-
|
|
5493
|
-
|
|
5850
|
+
trust: {
|
|
5851
|
+
async grants() {
|
|
5852
|
+
return Object.values((await read()).grants).map(storedGrant);
|
|
5853
|
+
},
|
|
5854
|
+
async token(hash) {
|
|
5855
|
+
const state = await read();
|
|
5856
|
+
const id = state.hashes[hash];
|
|
5857
|
+
if (id === void 0 || !liveIn(state, id)) return null;
|
|
5858
|
+
const row = state.tokens[id];
|
|
5859
|
+
return {
|
|
5860
|
+
id: tokenId(row.id),
|
|
5861
|
+
name: row.name,
|
|
5862
|
+
minter: row.minter,
|
|
5863
|
+
pinned: {
|
|
5864
|
+
profile: row.profile,
|
|
5865
|
+
avatar: row.avatar,
|
|
5866
|
+
session: row.session,
|
|
5867
|
+
handle: row.handle,
|
|
5868
|
+
name: row.personName
|
|
5869
|
+
},
|
|
5870
|
+
expiresAt: new Date(row.expiresAt)
|
|
5871
|
+
};
|
|
5872
|
+
},
|
|
5873
|
+
async live(id) {
|
|
5874
|
+
const index = indexOf(id, "t");
|
|
5875
|
+
return index !== null && liveIn(await read(), index);
|
|
5876
|
+
}
|
|
5877
|
+
},
|
|
5878
|
+
async grants(identity) {
|
|
5879
|
+
mayList(identity, "list grants");
|
|
5880
|
+
return { grants: Object.values((await read()).grants).sort((a, b) => a.id - b.id).map(grantView) };
|
|
5881
|
+
},
|
|
5882
|
+
async createGrant(identity, body) {
|
|
5883
|
+
const team = await options.team();
|
|
5884
|
+
const [row] = await whileHeadMoves(async () => {
|
|
5885
|
+
const { state, index } = await latest();
|
|
5886
|
+
const checked = checkGrant(body, grantIssuers(Object.values(state.grants).map(storedGrant)), team);
|
|
5887
|
+
const before = Object.values(state.grants).map(storedGrant);
|
|
5888
|
+
const after = [...before, checked];
|
|
5889
|
+
await mayGrant(identity, { changed: checked }, before, after, accessIn);
|
|
5890
|
+
if (namesIssuer(checked.principals)) await mayGrant(identity, { changed: { can: { "*": "all" } } }, before, after, accessIn, "naming an oidc issuer");
|
|
5891
|
+
return session.append.ifLastIndex(index, {
|
|
5892
|
+
type: "grant.created",
|
|
5893
|
+
payload: {
|
|
5894
|
+
principals: checked.principals,
|
|
5895
|
+
can: checked.can,
|
|
5896
|
+
by: identity.actor.id
|
|
5897
|
+
}
|
|
5898
|
+
});
|
|
5899
|
+
});
|
|
5900
|
+
const made = row && Object.values((await read()).grants).find((grant) => grant.event === row.index);
|
|
5901
|
+
if (!made) throw new Error("a grant was made but its log has no record of it");
|
|
5902
|
+
return { grant: grantView(made) };
|
|
5903
|
+
},
|
|
5904
|
+
async updateGrant(identity, input) {
|
|
5905
|
+
const team = await options.team();
|
|
5906
|
+
const id = await whileHeadMoves(async () => {
|
|
5907
|
+
const { state, index } = await latest();
|
|
5908
|
+
const event = await updated(identity, state, input, [], accessIn, team);
|
|
5909
|
+
await session.append.ifLastIndex(index, event);
|
|
5910
|
+
return event.payload.id;
|
|
5911
|
+
});
|
|
5912
|
+
return { grant: grantView((await read()).grants[id]) };
|
|
5913
|
+
},
|
|
5914
|
+
async explain(identity, query) {
|
|
5915
|
+
const named = query.user !== void 0 || query.project !== void 0 || query.github !== void 0 || query.oidc !== void 0 || query.app !== void 0;
|
|
5916
|
+
if (named) mayList(identity, "explain what another principal may do");
|
|
5917
|
+
if (query.app !== void 0) return {
|
|
5918
|
+
channel: query.channel,
|
|
5919
|
+
pattern: null,
|
|
5920
|
+
over: [],
|
|
5921
|
+
level: null,
|
|
5922
|
+
grants: [],
|
|
5923
|
+
capped: null,
|
|
5924
|
+
can: []
|
|
5925
|
+
};
|
|
5926
|
+
const { id, kind, handle, facts, scope, token } = identity.principal;
|
|
5927
|
+
const principal = named ? principalNamed(query, await options.team()) : {
|
|
5928
|
+
id,
|
|
5929
|
+
kind,
|
|
5930
|
+
handle,
|
|
5931
|
+
...facts ? { facts } : {},
|
|
5932
|
+
...scope !== void 0 ? { scope } : {},
|
|
5933
|
+
...token !== void 0 ? { token } : {}
|
|
5934
|
+
};
|
|
5935
|
+
const decided = await options.explain(principal, query.channel);
|
|
5936
|
+
const { grants } = await read();
|
|
5937
|
+
const shown = lists(identity) ? decided.grants : [];
|
|
5938
|
+
return {
|
|
5939
|
+
channel: query.channel,
|
|
5940
|
+
pattern: decided.pattern,
|
|
5941
|
+
over: decided.over,
|
|
5942
|
+
level: decided.level,
|
|
5943
|
+
grants: shown.flatMap((grant) => {
|
|
5944
|
+
const row = grants[indexOf(grant.id, "g") ?? 0];
|
|
5945
|
+
return row ? [grantView(row)] : [];
|
|
5946
|
+
}),
|
|
5947
|
+
capped: null,
|
|
5948
|
+
can: decided.permissions
|
|
5949
|
+
};
|
|
5950
|
+
},
|
|
5951
|
+
async revokeGrant(identity, { id }) {
|
|
5952
|
+
return whileHeadMoves(async () => {
|
|
5953
|
+
const { state, index } = await latest();
|
|
5954
|
+
const at = indexOf(id, "g");
|
|
5955
|
+
const row = at === null ? void 0 : state.grants[at];
|
|
5956
|
+
if (!row) {
|
|
5957
|
+
mayList(identity, "revoke grants");
|
|
5958
|
+
return { revoked: false };
|
|
5959
|
+
}
|
|
5960
|
+
const before = Object.values(state.grants).map(storedGrant);
|
|
5961
|
+
await mayGrant(identity, { revoked: row }, before, before.filter((other) => other.id !== storedGrant(row).id), accessIn, `revoke ${id}`);
|
|
5962
|
+
await session.append.ifLastIndex(index, {
|
|
5963
|
+
type: "grant.deleted",
|
|
5964
|
+
payload: {
|
|
5965
|
+
id: row.id,
|
|
5966
|
+
by: identity.actor.id
|
|
5967
|
+
}
|
|
5968
|
+
});
|
|
5969
|
+
return { revoked: true };
|
|
5970
|
+
});
|
|
5971
|
+
},
|
|
5972
|
+
async tokens(identity) {
|
|
5973
|
+
const state = await read();
|
|
5974
|
+
return { tokens: await viewsOf(Object.values(state.tokens).filter((row) => liveIn(state, row.id) && manages(state, identity, row)).sort((a, b) => a.id - b.id)) };
|
|
5975
|
+
},
|
|
5976
|
+
/** The board tokens `principal` came with: its own, then each it was minted with. Undefined with none. */
|
|
5977
|
+
async chain(principal) {
|
|
5978
|
+
if (principal.token === void 0) return void 0;
|
|
5979
|
+
const state = await read();
|
|
5980
|
+
const chain = [];
|
|
5981
|
+
for (let at = indexOf(principal.token, "t"); at !== null && chain.length <= TOKEN_DEPTH_MAX; at = state.tokens[at]?.parent ?? null) chain.push(tokenId(at));
|
|
5982
|
+
return chain;
|
|
5983
|
+
},
|
|
5984
|
+
async createToken(identity, body) {
|
|
5985
|
+
const { principal, author, actor } = identity;
|
|
5986
|
+
const state = await read();
|
|
5987
|
+
const now = Date.now();
|
|
5988
|
+
const asked = body.expires === void 0 ? TOKEN_DEFAULT_MS : duration(body.expires);
|
|
5989
|
+
if (asked <= 0 || asked > 7776e6) throw badRequest("a token lives up to 90 days: pass expires as 90d or less", "invalid_expires");
|
|
5990
|
+
let expiresAt = now + asked;
|
|
5991
|
+
let parent = null;
|
|
5992
|
+
if (principal.token !== void 0) {
|
|
5993
|
+
const index = indexOf(principal.token, "t");
|
|
5994
|
+
parent = index === null ? null : state.tokens[index] ?? null;
|
|
5995
|
+
if (!parent || !liveIn(state, parent.id)) throw unauthorized("invalid token: revoked, expired, or not this board's");
|
|
5996
|
+
let depth = 0;
|
|
5997
|
+
for (let at = parent; at; at = at.parent === null ? void 0 : state.tokens[at.parent]) depth++;
|
|
5998
|
+
if (depth >= TOKEN_DEPTH_MAX) throw badRequest(`tokens minted with tokens go ${TOKEN_DEPTH_MAX} deep at most`, "invalid_token");
|
|
5999
|
+
expiresAt = Math.min(expiresAt, parent.expiresAt);
|
|
6000
|
+
}
|
|
6001
|
+
let can;
|
|
6002
|
+
try {
|
|
6003
|
+
can = compileAccess(body.can ?? DEFAULT_CAN);
|
|
6004
|
+
} catch (error) {
|
|
6005
|
+
throw badRequest(error.message, "invalid_scope");
|
|
6006
|
+
}
|
|
6007
|
+
const scope = scopeOf((principal.scope === void 0 ? FULL_ACCESS : compileAccess(parseScope(principal.scope))).narrow(can));
|
|
6008
|
+
if (scope.length > 4e3) throw badRequest(`a token's can is ${SCOPE_MAX} characters at most as a scope: name fewer channels`, "invalid_scope");
|
|
6009
|
+
const minter = {
|
|
6010
|
+
id: principal.id,
|
|
6011
|
+
kind: principal.kind,
|
|
6012
|
+
handle: principal.handle,
|
|
6013
|
+
...principal.facts ? { facts: principal.facts } : {},
|
|
6014
|
+
scope
|
|
6015
|
+
};
|
|
6016
|
+
const pinned = principal.pinned;
|
|
6017
|
+
const profile = pinned?.profile ?? body.profile ?? null;
|
|
6018
|
+
const avatar = pinned?.profile ? pinned.avatar : profile !== null ? body.avatar ?? null : null;
|
|
6019
|
+
const pinnedSession = pinned?.session ?? body.session ?? null;
|
|
6020
|
+
const person = principal.kind === "person";
|
|
6021
|
+
const base = author.profile === null ? actor.handle : actor.handle.slice(0, Math.max(0, actor.handle.length - author.profile.length - 1)) || principal.handle;
|
|
6022
|
+
const handle = pinned?.handle ?? (person ? base : null);
|
|
6023
|
+
const personName = pinned?.name ?? (person && author.profile === null ? actor.name : null);
|
|
6024
|
+
const secret = newSecret();
|
|
6025
|
+
const [row] = await session.append({
|
|
6026
|
+
type: "token.minted",
|
|
6027
|
+
payload: {
|
|
6028
|
+
hash: await tokenHash(secret),
|
|
6029
|
+
name: body.name,
|
|
6030
|
+
minter,
|
|
6031
|
+
profile,
|
|
6032
|
+
avatar,
|
|
6033
|
+
session: pinnedSession,
|
|
6034
|
+
handle,
|
|
6035
|
+
personName,
|
|
6036
|
+
expiresAt,
|
|
6037
|
+
parent: parent?.id ?? null,
|
|
6038
|
+
by: actor.id
|
|
6039
|
+
}
|
|
6040
|
+
});
|
|
6041
|
+
const minted = row && (await read()).tokens[row.index];
|
|
6042
|
+
if (!minted) throw new Error("a token was minted but its log has no record of it");
|
|
6043
|
+
const [view] = await viewsOf([minted]);
|
|
6044
|
+
return {
|
|
6045
|
+
token: view,
|
|
6046
|
+
secret
|
|
6047
|
+
};
|
|
6048
|
+
},
|
|
6049
|
+
async revokeToken(identity, { id }) {
|
|
6050
|
+
const state = await read();
|
|
6051
|
+
const index = indexOf(id, "t");
|
|
6052
|
+
const row = index === null ? void 0 : state.tokens[index];
|
|
6053
|
+
if (!row || !liveIn(state, row.id) || !manages(state, identity, row)) return { revoked: false };
|
|
6054
|
+
await session.append({
|
|
6055
|
+
type: "token.revoked",
|
|
6056
|
+
payload: {
|
|
6057
|
+
id: row.id,
|
|
6058
|
+
by: identity.actor.id
|
|
6059
|
+
}
|
|
6060
|
+
});
|
|
6061
|
+
return { revoked: true };
|
|
6062
|
+
}
|
|
5494
6063
|
};
|
|
5495
6064
|
}
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
* since addressing a thread you can't see would confirm it exists.
|
|
5502
|
-
*/
|
|
5503
|
-
async function authorizePost(ctx, access, input) {
|
|
5504
|
-
let channel;
|
|
5505
|
-
let re;
|
|
5506
|
-
if (input.re !== void 0) {
|
|
5507
|
-
re = (await authorizeMessage(ctx, access, "read", input.re)).message;
|
|
5508
|
-
channel = re.channel;
|
|
5509
|
-
} else {
|
|
5510
|
-
if (!input.channel) throw badRequest("a post needs a channel");
|
|
5511
|
-
channel = input.channel;
|
|
5512
|
-
}
|
|
6065
|
+
//#endregion
|
|
6066
|
+
//#region src/server/blob.ts
|
|
6067
|
+
/** Files in memory, for tests: forgets everything when the process ends. */
|
|
6068
|
+
function memoryBlob() {
|
|
6069
|
+
const files = /* @__PURE__ */ new Map();
|
|
5513
6070
|
return {
|
|
5514
|
-
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
6071
|
+
put: async (key, data, contentType) => void files.set(key, {
|
|
6072
|
+
data: data.slice(),
|
|
6073
|
+
contentType
|
|
6074
|
+
}),
|
|
6075
|
+
get: async (key) => files.get(key) ?? null
|
|
5518
6076
|
};
|
|
5519
6077
|
}
|
|
5520
|
-
/**
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
*/
|
|
5524
|
-
function spend(proof, permission, target) {
|
|
5525
|
-
if (!proof || proof.permission !== permission || proof.channel !== target.channel) throw new Error(`a ${permission} write in ${target.channel} needs a proof for that channel`);
|
|
5526
|
-
}
|
|
5527
|
-
/** Full-access proofs for the board's own code (sync), still checked against the channel each write lands in. */
|
|
5528
|
-
const trusted = {
|
|
5529
|
-
message: (ctx, permission, id) => authorizeMessage(ctx, FULL_ACCESS, permission, id),
|
|
5530
|
-
post: (ctx, input) => authorizePost(ctx, FULL_ACCESS, input)
|
|
5531
|
-
};
|
|
5532
|
-
async function writePost(ctx, input) {
|
|
5533
|
-
const { identity } = input;
|
|
5534
|
-
const sent = input.text;
|
|
5535
|
-
let channel = input.channel;
|
|
5536
|
-
let re = null;
|
|
5537
|
-
let replyTo = null;
|
|
5538
|
-
let thread;
|
|
5539
|
-
const id = input.id ?? (input.re === void 0 ? crypto.randomUUID() : void 0);
|
|
5540
|
-
if (input.re !== void 0) {
|
|
5541
|
-
const target = input.proofs.re;
|
|
5542
|
-
if (target?.id !== input.re) throw new Error(`a reply to #${input.re} needs proofs for that message`);
|
|
5543
|
-
re = target.re ?? target.id;
|
|
5544
|
-
replyTo = target.id === re ? null : target.id;
|
|
5545
|
-
channel = target.channel;
|
|
5546
|
-
thread = target.thread;
|
|
5547
|
-
if (input.sync?.length) throw badRequest("sync attaches whole threads: use `board sync <id> <target>`");
|
|
5548
|
-
} else {
|
|
5549
|
-
if (!channel) throw badRequest("a post needs a channel");
|
|
5550
|
-
if (input.after !== void 0) throw badRequest("`after` is for replies", "invalid_after");
|
|
5551
|
-
thread = id;
|
|
5552
|
-
}
|
|
5553
|
-
spend(input.proofs.post, "post", { channel });
|
|
5554
|
-
if (hasLabels(input.labels)) spend(input.proofs.label, "label", { channel });
|
|
5555
|
-
if (input.sync?.length) spend(input.proofs.sync, "sync", { channel });
|
|
5556
|
-
const replayed = await replayOf(ctx, input, {
|
|
5557
|
-
channel,
|
|
5558
|
-
re,
|
|
5559
|
-
replyTo
|
|
5560
|
-
}, sent);
|
|
5561
|
-
if (replayed) return replayed;
|
|
5562
|
-
if (input.after !== void 0) {
|
|
5563
|
-
if ((await ctx.reads.message(input.after))?.thread !== thread) throw badRequest(`after names no message in #${re}'s thread`, "invalid_after");
|
|
5564
|
-
}
|
|
5565
|
-
return commitPost(ctx, input, {
|
|
5566
|
-
channel,
|
|
5567
|
-
re,
|
|
5568
|
-
replyTo,
|
|
5569
|
-
thread,
|
|
5570
|
-
id,
|
|
5571
|
-
sent
|
|
5572
|
-
});
|
|
5573
|
-
}
|
|
5574
|
-
/** The post a caller's own ID already landed, as its retry gets it back: null when there's none. */
|
|
5575
|
-
async function replayOf(ctx, input, place, sent) {
|
|
5576
|
-
if (input.id === void 0) return null;
|
|
5577
|
-
const landed = await ctx.reads.byEventId(input.id);
|
|
5578
|
-
if (!landed) return null;
|
|
5579
|
-
if (landed.channel !== place.channel || landed.re !== place.re || landed.replyTo !== place.replyTo) throw duplicateId();
|
|
5580
|
-
const shown = await landedFor(ctx, input.identity, landed);
|
|
5581
|
-
if (!shown) throw duplicateId();
|
|
5582
|
-
return shownTo(shown, input.identity.principal.access, sent);
|
|
5583
|
-
}
|
|
5584
|
-
/**
|
|
5585
|
-
* A post that landed, as its author may have it back: only the same author's, and one in a
|
|
5586
|
-
* channel it can't read only if it posted without reading too. A caller that can't read gets back
|
|
5587
|
-
* what it sent, as it landed: never what others have added since. Null for anyone else.
|
|
5588
|
-
*/
|
|
5589
|
-
async function landedFor(ctx, identity, landed) {
|
|
5590
|
-
if (!sameAuthor(landed.by, identity.author)) return null;
|
|
5591
|
-
const { access } = identity.principal;
|
|
5592
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5593
|
-
if (access.readable(landed.channel)) return view(landed, actors, await readerFor(ctx, access, landed));
|
|
5594
|
-
if (!landed.blind) return null;
|
|
5595
|
-
const [event] = await ctx.session.history({
|
|
5596
|
-
gte: landed.id,
|
|
5597
|
-
lte: landed.id
|
|
5598
|
-
});
|
|
5599
|
-
const posted = foldMessages({
|
|
5600
|
-
byId: {},
|
|
5601
|
-
replies: {}
|
|
5602
|
-
}, event).byId[landed.id];
|
|
6078
|
+
/** Files on disk, under `dir`: a local board's, next to its database. */
|
|
6079
|
+
function fsBlob(dir) {
|
|
6080
|
+
const path = (key) => join(dir, ...key.split("/"));
|
|
5603
6081
|
return {
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
}
|
|
5609
|
-
/**
|
|
5610
|
-
* A message's text for its writer where it can't read: each exact mention but of itself shows as
|
|
5611
|
-
* `@…`. The board may have turned an email it wrote into an actor ID, and who that is, `/actors`
|
|
5612
|
-
* doesn't show it either.
|
|
5613
|
-
*/
|
|
5614
|
-
const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
|
|
5615
|
-
const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile && a.session === b.session;
|
|
5616
|
-
async function commitPost(ctx, input, placed) {
|
|
5617
|
-
const { identity } = input;
|
|
5618
|
-
const { channel, re, replyTo, thread, id, sent } = placed;
|
|
5619
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5620
|
-
const targets = [];
|
|
5621
|
-
if (re === null) for (const requested of input.sync ?? []) {
|
|
5622
|
-
const target = syncTarget(requested);
|
|
5623
|
-
await unclaimed(ctx, target, thread, identity.principal.access);
|
|
5624
|
-
if (!targets.some((t) => t.target === target.target)) targets.push({
|
|
5625
|
-
...target,
|
|
5626
|
-
cause: "request"
|
|
5627
|
-
});
|
|
5628
|
-
}
|
|
5629
|
-
const seen = seenFor(identity, actors);
|
|
5630
|
-
const { text, found } = await withEmailMentions(input.text);
|
|
5631
|
-
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
5632
|
-
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? identity.actor : void 0, input.lenientMentions ?? false, identity.principal.access.readsAll);
|
|
5633
|
-
const synced = await Promise.all(targets.map(async ({ target, kind, cause }) => ({
|
|
5634
|
-
type: "thread.synced",
|
|
5635
|
-
id: await derivedId("board", thread, "sync", target),
|
|
5636
|
-
payload: {
|
|
5637
|
-
thread,
|
|
5638
|
-
target,
|
|
5639
|
-
kind,
|
|
5640
|
-
cause,
|
|
5641
|
-
by: identity.author
|
|
5642
|
-
}
|
|
5643
|
-
})));
|
|
5644
|
-
const events = [
|
|
5645
|
-
...seen ? [seen] : [],
|
|
5646
|
-
...named,
|
|
5647
|
-
{
|
|
5648
|
-
type: "message.posted",
|
|
5649
|
-
...id ? { id } : {},
|
|
5650
|
-
payload: {
|
|
5651
|
-
channel,
|
|
5652
|
-
text,
|
|
5653
|
-
re,
|
|
5654
|
-
replyTo,
|
|
5655
|
-
thread,
|
|
5656
|
-
labels: input.labels ?? {},
|
|
5657
|
-
noSync: input.noSync ?? false,
|
|
5658
|
-
mentions,
|
|
5659
|
-
by: identity.author,
|
|
5660
|
-
origin: input.origin ?? null,
|
|
5661
|
-
from: input.from ?? null,
|
|
5662
|
-
...input.attachments?.length ? { attachments: input.attachments } : {},
|
|
5663
|
-
...input.links?.length ? { links: input.links } : {},
|
|
5664
|
-
...input.schedule ? { schedule: input.schedule } : {},
|
|
5665
|
-
...identity.principal.access.readable(channel) ? {} : { blind: true },
|
|
5666
|
-
...input.importedBy !== void 0 ? { importedBy: input.importedBy } : {}
|
|
5667
|
-
}
|
|
6082
|
+
async put(key, data, contentType) {
|
|
6083
|
+
await mkdir(dirname(path(key)), { recursive: true });
|
|
6084
|
+
await writeFile(path(key), data);
|
|
6085
|
+
await writeFile(`${path(key)}.type`, contentType);
|
|
5668
6086
|
},
|
|
5669
|
-
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
5675
|
-
|
|
5676
|
-
|
|
5677
|
-
|
|
5678
|
-
|
|
5679
|
-
}, sent) : null;
|
|
5680
|
-
if (replayed) return replayed;
|
|
5681
|
-
throw error;
|
|
5682
|
-
}
|
|
5683
|
-
const posted = rows.find((row) => row.type === "message.posted");
|
|
5684
|
-
await untilApplied(ctx, rows);
|
|
5685
|
-
const message = foldMessages({
|
|
5686
|
-
byId: {},
|
|
5687
|
-
replies: {}
|
|
5688
|
-
}, posted).byId[posted.index];
|
|
5689
|
-
const known = seen ? {
|
|
5690
|
-
...actors,
|
|
5691
|
-
byId: {
|
|
5692
|
-
...actors.byId,
|
|
5693
|
-
[identity.actor.id]: identity.actor
|
|
6087
|
+
async get(key) {
|
|
6088
|
+
try {
|
|
6089
|
+
const [data, contentType] = await Promise.all([readFile(path(key)), readFile(`${path(key)}.type`, "utf8")]);
|
|
6090
|
+
return {
|
|
6091
|
+
data: new Uint8Array(data),
|
|
6092
|
+
contentType
|
|
6093
|
+
};
|
|
6094
|
+
} catch {
|
|
6095
|
+
return null;
|
|
6096
|
+
}
|
|
5694
6097
|
}
|
|
5695
|
-
}
|
|
5696
|
-
|
|
6098
|
+
};
|
|
6099
|
+
}
|
|
6100
|
+
const dataKey = (id) => `board/attachments/${id}`;
|
|
6101
|
+
/** A direct upload the board signed, until it's finished: what it's called, and who may finish it. */
|
|
6102
|
+
const ticketKey = (id) => `board/uploads/${id}.json`;
|
|
6103
|
+
const metaKey = (id) => `board/attachments/${id}.json`;
|
|
6104
|
+
/** A board without a blob store keeps no files: every file route says so. */
|
|
6105
|
+
const noBlob = () => new HttpError(501, "no_files", "this board keeps no files");
|
|
6106
|
+
/** 128 random bits, base64url, drawn again when they'd start with `-`, which a command line reads as a flag. */
|
|
6107
|
+
function attachmentId() {
|
|
6108
|
+
for (;;) {
|
|
6109
|
+
const id = randomBytes(16).toString("base64url");
|
|
6110
|
+
if (!id.startsWith("-")) return id;
|
|
6111
|
+
}
|
|
5697
6112
|
}
|
|
5698
6113
|
/**
|
|
5699
|
-
*
|
|
5700
|
-
*
|
|
5701
|
-
*
|
|
5702
|
-
*
|
|
5703
|
-
* mentions, so they still notify.
|
|
5704
|
-
*/
|
|
5705
|
-
const shownTo = (shown, access, sent, unknown = []) => !access.readable(shown.channel) ? {
|
|
5706
|
-
...shown,
|
|
5707
|
-
text: sent,
|
|
5708
|
-
mentions: []
|
|
5709
|
-
} : unknown.length ? {
|
|
5710
|
-
...shown,
|
|
5711
|
-
unknownMentions: unknown
|
|
5712
|
-
} : shown;
|
|
5713
|
-
/** The writer, as the reader of the view its write returns. Only a link to a board message needs a lookup. */
|
|
5714
|
-
const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
|
|
5715
|
-
/**
|
|
5716
|
-
* Refuses an external thread another board thread is synced with: taking it
|
|
5717
|
-
* over would send its replies away from that thread, to a caller who may not
|
|
5718
|
-
* read it. A reader of that thread's channel learns which thread it is. It
|
|
5719
|
-
* reads the tables once they've applied the whole log, so a sync just made
|
|
5720
|
-
* counts.
|
|
6114
|
+
* Whether an upload is the caller's own, to read and attach before a message carries it: its
|
|
6115
|
+
* principal sent it, and the caller holds no board token, or holds the one it came with or one
|
|
6116
|
+
* that token was minted with. A token acts as its minter, so the principal alone would hand it
|
|
6117
|
+
* every file its minter, or another of its minter's tokens, uploaded.
|
|
5721
6118
|
*/
|
|
5722
|
-
|
|
5723
|
-
if (
|
|
5724
|
-
|
|
5725
|
-
const owner = await ctx.reads.tables.threadOf(target.target);
|
|
5726
|
-
if (owner === null || owner === thread) return;
|
|
5727
|
-
const synced = await ctx.reads.tables.syncOf(owner);
|
|
5728
|
-
const which = synced && access.readable(synced.channel) ? `#${synced.root}` : "another thread";
|
|
5729
|
-
throw new HttpError(409, "already_synced", `${target.target} is already synced with ${which}`);
|
|
6119
|
+
function ownUpload(upload, caller) {
|
|
6120
|
+
if (upload.uploadedBy !== caller.id) return false;
|
|
6121
|
+
return caller.token === void 0 || (upload.uploadedWith?.includes(caller.token) ?? false);
|
|
5730
6122
|
}
|
|
5731
6123
|
/**
|
|
5732
|
-
*
|
|
5733
|
-
*
|
|
5734
|
-
*
|
|
5735
|
-
*
|
|
6124
|
+
* Stores an upload under a fresh ID, with its metadata beside it. `uploadedBy`
|
|
6125
|
+
* is the principal that sent it, who can read it before any message carries it,
|
|
6126
|
+
* and `uploadedWith` the board tokens it came with (`ownUpload`).
|
|
6127
|
+
* `max` is the most it can be: `ATTACHMENT_BYTES_MAX` unless the board's own sync imports it.
|
|
5736
6128
|
*/
|
|
5737
|
-
async function
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
|
|
5743
|
-
|
|
5744
|
-
|
|
5745
|
-
|
|
5746
|
-
|
|
5747
|
-
|
|
6129
|
+
async function writeUpload(blob, input, max = ATTACHMENT_BYTES_MAX) {
|
|
6130
|
+
if (!blob) throw noBlob();
|
|
6131
|
+
if (input.data.byteLength === 0) throw badRequest("the file is empty");
|
|
6132
|
+
if (input.data.byteLength > max) throw new HttpError(413, "too_large", `attachments are at most ${max / 1024 / 1024} MB`);
|
|
6133
|
+
const attachment = {
|
|
6134
|
+
id: attachmentId(),
|
|
6135
|
+
name: fileName(input.name),
|
|
6136
|
+
type: mediaType(input.type),
|
|
6137
|
+
size: input.data.byteLength
|
|
6138
|
+
};
|
|
6139
|
+
await blob.put(dataKey(attachment.id), input.data, attachment.type);
|
|
6140
|
+
const meta = input.uploadedBy === void 0 ? attachment : {
|
|
6141
|
+
...attachment,
|
|
6142
|
+
uploadedBy: input.uploadedBy,
|
|
6143
|
+
...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {}
|
|
6144
|
+
};
|
|
6145
|
+
await blob.put(metaKey(attachment.id), new TextEncoder().encode(JSON.stringify(meta)), "application/json");
|
|
6146
|
+
return attachment;
|
|
5748
6147
|
}
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
/**
|
|
5752
|
-
* Appends `events` only while the board, as `holds` reads it, still allows them: `holds` checks
|
|
5753
|
-
* the tables, throws what refuses the write, and returns the index its reads reflect. The append
|
|
5754
|
-
* holds only while that index is still the log's last, so anything that lands in between,
|
|
5755
|
-
* anywhere on the board, moves it, and it looks again from there.
|
|
5756
|
-
*/
|
|
5757
|
-
async function appendWhile(ctx, holds, events) {
|
|
5758
|
-
return whileHeadMoves(async () => {
|
|
5759
|
-
await ctx.reads.ensure();
|
|
5760
|
-
return appendIfLast(ctx.session, await holds(), events);
|
|
5761
|
-
});
|
|
6148
|
+
async function bytes(data) {
|
|
6149
|
+
return data instanceof Uint8Array ? data : new Uint8Array(await new Response(data).arrayBuffer());
|
|
5762
6150
|
}
|
|
6151
|
+
const attachmentNotFound = (id) => notFound(`no attachment: ${id}`, "attachment_not_found");
|
|
5763
6152
|
/**
|
|
5764
|
-
*
|
|
5765
|
-
*
|
|
6153
|
+
* An upload's metadata, as the board recorded it, never what a request says,
|
|
6154
|
+
* and who uploaded it: null for files the board imported itself, or stored
|
|
6155
|
+
* before it recorded that.
|
|
5766
6156
|
*/
|
|
5767
|
-
async function
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
|
|
5778
|
-
|
|
5779
|
-
|
|
5780
|
-
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
|
|
5784
|
-
|
|
5785
|
-
|
|
5786
|
-
|
|
5787
|
-
|
|
5788
|
-
|
|
5789
|
-
spend(authorized.proof, permission, authorized.message);
|
|
5790
|
-
return authorized.message;
|
|
5791
|
-
}
|
|
5792
|
-
async function writeEdit(ctx, input) {
|
|
5793
|
-
const message = spent(input.authorized, "post");
|
|
5794
|
-
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can edit a message");
|
|
5795
|
-
if (message.deleted) {
|
|
5796
|
-
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
5797
|
-
throw badRequest("message was deleted", "message_deleted");
|
|
5798
|
-
}
|
|
5799
|
-
return commitEdit(ctx, input, message);
|
|
5800
|
-
}
|
|
5801
|
-
async function commitEdit(ctx, input, message) {
|
|
5802
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5803
|
-
const seen = seenFor(input.identity, actors);
|
|
5804
|
-
const { text, found } = await withEmailMentions(input.text);
|
|
5805
|
-
const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
|
|
5806
|
-
const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? input.identity.actor : void 0, input.from != null, input.identity.principal.access.readsAll);
|
|
5807
|
-
const events = [
|
|
5808
|
-
...seen ? [seen] : [],
|
|
5809
|
-
...named,
|
|
5810
|
-
{
|
|
5811
|
-
type: "message.edited",
|
|
5812
|
-
payload: {
|
|
5813
|
-
id: message.id,
|
|
5814
|
-
thread: message.thread,
|
|
5815
|
-
text,
|
|
5816
|
-
mentions,
|
|
5817
|
-
by: input.identity.author,
|
|
5818
|
-
from: input.from ?? null
|
|
5819
|
-
}
|
|
5820
|
-
}
|
|
5821
|
-
];
|
|
5822
|
-
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
|
|
5823
|
-
return unknown.length && input.identity.principal.access.readable(message.channel) ? { unknownMentions: unknown } : {};
|
|
5824
|
-
}
|
|
5825
|
-
/** A message's links, replaced: a platform edit or unfurl changed what it links to. */
|
|
5826
|
-
async function writeLinks(ctx, input) {
|
|
5827
|
-
const message = spent(input.authorized, "post");
|
|
5828
|
-
if (message.deleted) return;
|
|
5829
|
-
await untilApplied(ctx, await ctx.session.append({
|
|
5830
|
-
type: "message.linked",
|
|
5831
|
-
payload: {
|
|
5832
|
-
id: message.id,
|
|
5833
|
-
thread: message.thread,
|
|
5834
|
-
links: input.links,
|
|
5835
|
-
by: input.identity.author,
|
|
5836
|
-
from: input.from
|
|
5837
|
-
}
|
|
5838
|
-
}));
|
|
5839
|
-
}
|
|
5840
|
-
async function writeDelete(ctx, input) {
|
|
5841
|
-
const message = spent(input.authorized, "post");
|
|
5842
|
-
if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can delete a message");
|
|
5843
|
-
if (message.deleted) {
|
|
5844
|
-
if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
|
|
5845
|
-
return;
|
|
5846
|
-
}
|
|
5847
|
-
const deleted = [{
|
|
5848
|
-
type: "message.deleted",
|
|
5849
|
-
payload: {
|
|
5850
|
-
id: message.id,
|
|
5851
|
-
thread: message.thread,
|
|
5852
|
-
by: input.identity.author,
|
|
5853
|
-
from: input.from ?? null
|
|
5854
|
-
}
|
|
5855
|
-
}];
|
|
5856
|
-
await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...deleted) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), deleted));
|
|
5857
|
-
}
|
|
5858
|
-
/** An edit's or a delete's `revision`: no edit or delete since, as of the index the read reflects. */
|
|
5859
|
-
const revisionIs = (ctx, id, revision) => async () => {
|
|
5860
|
-
const position = await ctx.reads.tables.position();
|
|
5861
|
-
const message = (await ctx.reads.tables.messagesAt([id], position)).get(id);
|
|
5862
|
-
const now = message ? message.revision ?? message.id : null;
|
|
5863
|
-
if (now !== revision) throw new HttpError(409, "revision_conflict", message?.deleted ? `#${id} was deleted since revision ${revision}` : `#${id} was edited since revision ${revision}: it's at ${now}`);
|
|
5864
|
-
return position;
|
|
5865
|
-
};
|
|
5866
|
-
async function writeReaction(ctx, input) {
|
|
5867
|
-
const message = spent(input.authorized, "react");
|
|
5868
|
-
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
5869
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5870
|
-
const seen = seenFor(input.identity, actors);
|
|
5871
|
-
await untilApplied(ctx, await ctx.session.append(...seen ? [seen] : [], {
|
|
5872
|
-
type: input.remove ? "reaction.removed" : "reaction.added",
|
|
5873
|
-
payload: {
|
|
5874
|
-
id: message.id,
|
|
5875
|
-
thread: message.thread,
|
|
5876
|
-
emoji: input.emoji,
|
|
5877
|
-
by: input.identity.author,
|
|
5878
|
-
from: input.from ?? null
|
|
5879
|
-
}
|
|
5880
|
-
}));
|
|
5881
|
-
}
|
|
5882
|
-
async function writeLabels(ctx, input) {
|
|
5883
|
-
const message = spent(input.authorized, "label");
|
|
5884
|
-
if (message.deleted) throw badRequest("message was deleted", "message_deleted");
|
|
5885
|
-
const { state: actors } = await ctx.session.state(actorsReducer);
|
|
5886
|
-
const seen = seenFor(input.identity, actors);
|
|
5887
|
-
const events = [...seen ? [seen] : [], {
|
|
5888
|
-
type: "labels.changed",
|
|
5889
|
-
payload: {
|
|
5890
|
-
id: message.id,
|
|
5891
|
-
thread: message.thread,
|
|
5892
|
-
set: input.set ?? {},
|
|
5893
|
-
unset: input.unset ?? [],
|
|
5894
|
-
by: input.identity.author
|
|
5895
|
-
}
|
|
5896
|
-
}];
|
|
5897
|
-
await untilApplied(ctx, input.if !== void 0 && Object.keys(input.if).length > 0 ? await appendWhile(ctx, labelsAre(ctx, message.id, input.if), events) : await ctx.session.append(...events));
|
|
5898
|
-
}
|
|
5899
|
-
/** A label write's `if`: each label is as it says, as of the index the read reflects. */
|
|
5900
|
-
const labelsAre = (ctx, id, expected) => async () => {
|
|
5901
|
-
const position = await ctx.reads.tables.position();
|
|
5902
|
-
const labels = (await ctx.reads.tables.messagesAt([id], position)).get(id)?.labels ?? {};
|
|
5903
|
-
for (const key of Object.keys(expected).sort()) {
|
|
5904
|
-
const now = own(labels, key);
|
|
5905
|
-
if (now === expected[key] || now === void 0 && expected[key] === null) continue;
|
|
5906
|
-
const wanted = expected[key];
|
|
5907
|
-
throw new HttpError(409, "label_conflict", wanted === null ? `${key} is set` : now === void 0 ? `${key} isn't set` : `${key} isn't ${wanted}`);
|
|
5908
|
-
}
|
|
5909
|
-
return position;
|
|
5910
|
-
};
|
|
6157
|
+
async function readUpload(blob, id) {
|
|
6158
|
+
if (!blob) throw noBlob();
|
|
6159
|
+
const found = Attachment.shape.id.safeParse(id).success ? await blob.get(metaKey(id)) : null;
|
|
6160
|
+
if (!found) throw attachmentNotFound(id);
|
|
6161
|
+
const meta = JSON.parse(new TextDecoder().decode(await bytes(found.data)));
|
|
6162
|
+
const tokens = Array.isArray(meta.uploadedWith) && meta.uploadedWith.every((token) => typeof token === "string") ? meta.uploadedWith : null;
|
|
6163
|
+
return {
|
|
6164
|
+
attachment: Attachment.parse(meta),
|
|
6165
|
+
uploadedBy: typeof meta.uploadedBy === "string" ? meta.uploadedBy : null,
|
|
6166
|
+
uploadedWith: tokens
|
|
6167
|
+
};
|
|
6168
|
+
}
|
|
6169
|
+
/** An attachment's bytes as the store keeps them, a stream or the bytes, for board() to serve. */
|
|
6170
|
+
async function attachmentBody(blob, id) {
|
|
6171
|
+
if (!blob) throw noBlob();
|
|
6172
|
+
const found = await blob.get(dataKey(id));
|
|
6173
|
+
if (!found) throw attachmentNotFound(id);
|
|
6174
|
+
return found.data;
|
|
6175
|
+
}
|
|
6176
|
+
/** How long a direct upload's URL takes bytes: long enough for 100 MB on a slow link. */
|
|
6177
|
+
const DIRECT_UPLOAD_TTL_MS = 18e5;
|
|
6178
|
+
const noDirectUploads = () => new HttpError(501, "no_direct_uploads", `this board's blob store can't take direct uploads, so files are at most ${ATTACHMENT_BYTES_MAX / 1024 / 1024} MB`);
|
|
5911
6179
|
/**
|
|
5912
|
-
*
|
|
5913
|
-
*
|
|
6180
|
+
* Starts a direct upload: a fresh ID, and a URL in the store to `PUT` its bytes to. The board
|
|
6181
|
+
* keeps what the request said the file is until `finishUpload` checks the store has it.
|
|
5914
6182
|
*/
|
|
5915
|
-
async function
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
|
|
5921
|
-
|
|
5922
|
-
|
|
5923
|
-
|
|
5924
|
-
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
5932
|
-
|
|
6183
|
+
async function startUpload(blob, input) {
|
|
6184
|
+
if (!blob) throw noBlob();
|
|
6185
|
+
if (!blob.uploadUrl || !blob.head) throw noDirectUploads();
|
|
6186
|
+
if (input.size > 104857600) throw new HttpError(413, "too_large", `direct uploads are at most ${DIRECT_UPLOAD_BYTES_MAX / 1024 / 1024} MB`);
|
|
6187
|
+
const expires = new Date(Date.now() + DIRECT_UPLOAD_TTL_MS);
|
|
6188
|
+
const ticket = {
|
|
6189
|
+
id: attachmentId(),
|
|
6190
|
+
name: fileName(input.name),
|
|
6191
|
+
type: mediaType(input.type),
|
|
6192
|
+
size: input.size,
|
|
6193
|
+
uploadedBy: input.uploadedBy,
|
|
6194
|
+
...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {},
|
|
6195
|
+
expiresAt: expires.toISOString()
|
|
6196
|
+
};
|
|
6197
|
+
await blob.put(ticketKey(ticket.id), new TextEncoder().encode(JSON.stringify(ticket)), "application/json");
|
|
6198
|
+
const { url, headers } = await blob.uploadUrl(dataKey(ticket.id), {
|
|
6199
|
+
contentType: ticket.type,
|
|
6200
|
+
maxBytes: ticket.size,
|
|
6201
|
+
expiresAt: expires
|
|
6202
|
+
});
|
|
6203
|
+
return {
|
|
6204
|
+
id: ticket.id,
|
|
6205
|
+
url,
|
|
6206
|
+
headers: {
|
|
6207
|
+
...headers,
|
|
6208
|
+
"content-type": ticket.type
|
|
6209
|
+
},
|
|
6210
|
+
expiresAt: ticket.expiresAt
|
|
6211
|
+
};
|
|
5933
6212
|
}
|
|
5934
6213
|
/**
|
|
5935
|
-
*
|
|
5936
|
-
*
|
|
5937
|
-
*
|
|
6214
|
+
* Finishes a direct upload: once the store has exactly the bytes its start said, the board records
|
|
6215
|
+
* the attachment, as `writeUpload` does. Only its uploader may finish it (`ownUpload`); a second
|
|
6216
|
+
* finish answers the same attachment. It never reads the record before writing it: a store with a
|
|
6217
|
+
* cache (Vercel Blob's CDN) would keep that miss, and the post that names the file would find nothing.
|
|
5938
6218
|
*/
|
|
5939
|
-
async function
|
|
5940
|
-
|
|
5941
|
-
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
|
|
5945
|
-
|
|
5946
|
-
|
|
5947
|
-
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
5953
|
-
const found = own(state, input.path);
|
|
5954
|
-
return found ? { found } : { rows: await appendIfLast(ctx.session, index, events) };
|
|
5955
|
-
});
|
|
5956
|
-
if ("found" in made) return {
|
|
5957
|
-
channel: made.found,
|
|
5958
|
-
created: false
|
|
6219
|
+
async function finishUpload(blob, id, caller) {
|
|
6220
|
+
if (!blob) throw noBlob();
|
|
6221
|
+
const found = Attachment.shape.id.safeParse(id).success ? await blob.get(ticketKey(id)) : null;
|
|
6222
|
+
const ticket = found ? JSON.parse(new TextDecoder().decode(await bytes(found.data))) : null;
|
|
6223
|
+
if (!ticket || !ownUpload(ticket, caller)) throw notFound(`no upload: ${id}`, "upload_not_found");
|
|
6224
|
+
if (!blob.head) throw noDirectUploads();
|
|
6225
|
+
const stored = await blob.head(dataKey(id));
|
|
6226
|
+
if (!stored) throw new HttpError(409, "not_uploaded", `nothing's been uploaded for ${id} yet: PUT the file to its URL first`);
|
|
6227
|
+
if (stored.size !== ticket.size) throw badRequest(`the store has ${stored.size} bytes for ${id}, but its upload said ${ticket.size}`, "size_mismatch");
|
|
6228
|
+
const attachment = {
|
|
6229
|
+
id,
|
|
6230
|
+
name: ticket.name,
|
|
6231
|
+
type: ticket.type,
|
|
6232
|
+
size: stored.size
|
|
5959
6233
|
};
|
|
5960
|
-
|
|
6234
|
+
try {
|
|
6235
|
+
const uploader = {
|
|
6236
|
+
uploadedBy: ticket.uploadedBy,
|
|
6237
|
+
...ticket.uploadedWith ? { uploadedWith: ticket.uploadedWith } : {}
|
|
6238
|
+
};
|
|
6239
|
+
await blob.put(metaKey(id), new TextEncoder().encode(JSON.stringify({
|
|
6240
|
+
...attachment,
|
|
6241
|
+
...uploader
|
|
6242
|
+
})), "application/json");
|
|
6243
|
+
} catch (error) {
|
|
6244
|
+
const done = await blob.get(metaKey(id)).catch(() => null);
|
|
6245
|
+
if (!done) throw error;
|
|
6246
|
+
return Attachment.parse(JSON.parse(new TextDecoder().decode(await bytes(done.data))));
|
|
6247
|
+
}
|
|
6248
|
+
return attachment;
|
|
6249
|
+
}
|
|
6250
|
+
//#endregion
|
|
6251
|
+
//#region src/server/reads.ts
|
|
6252
|
+
/** Keeps the tables from the board's log, one event at a time, from the first. */
|
|
6253
|
+
function tablesConsumer(tables) {
|
|
6254
|
+
return consumer({
|
|
6255
|
+
contract: boardContract,
|
|
6256
|
+
name: TABLES_CONSUMER,
|
|
6257
|
+
lane: "tables",
|
|
6258
|
+
backfill: true
|
|
6259
|
+
}).run(async (ctx) => {
|
|
6260
|
+
if (ctx.session.id !== "board") return;
|
|
6261
|
+
await tables.apply(ctx.event);
|
|
6262
|
+
});
|
|
6263
|
+
}
|
|
6264
|
+
/**
|
|
6265
|
+
* The board's reads from its tables. A read that names a log index (a message
|
|
6266
|
+
* ID is one) waits until the tables have applied it; list reads don't wait, and
|
|
6267
|
+
* say which index they reflect.
|
|
6268
|
+
*/
|
|
6269
|
+
function createReads(tables, session, projection) {
|
|
6270
|
+
/**
|
|
6271
|
+
* The first list read on an instance starts the tables catching up, and doesn't wait: after a deploy
|
|
6272
|
+
* that adds them, or on a quiet board, nothing else may have yet.
|
|
6273
|
+
*/
|
|
6274
|
+
let catching = null;
|
|
6275
|
+
/**
|
|
6276
|
+
* The reader of views whose links point to the board messages `linked`, looked up only for a
|
|
6277
|
+
* reader that can't read every channel. A linked message is older than the one linking it, so
|
|
6278
|
+
* the tables have it.
|
|
6279
|
+
*/
|
|
6280
|
+
async function readerOf(access, linked) {
|
|
6281
|
+
if (access.readsAll) return {
|
|
6282
|
+
access,
|
|
6283
|
+
channelOf: () => void 0
|
|
6284
|
+
};
|
|
6285
|
+
const ids = [...new Set(linked)].filter((id) => id > 0);
|
|
6286
|
+
const found = ids.length === 0 ? /* @__PURE__ */ new Map() : await tables.messagesAt(ids, await tables.position());
|
|
6287
|
+
return {
|
|
6288
|
+
access,
|
|
6289
|
+
channelOf: (id) => found.get(id)?.channel
|
|
6290
|
+
};
|
|
6291
|
+
}
|
|
6292
|
+
function catchUp() {
|
|
6293
|
+
if (catching) return;
|
|
6294
|
+
catching = session.consume(projection).catch(() => {
|
|
6295
|
+
catching = null;
|
|
6296
|
+
});
|
|
6297
|
+
waitUntil(catching);
|
|
6298
|
+
}
|
|
6299
|
+
/**
|
|
6300
|
+
* The tables caught up with the whole log once on this instance. Until then, a read by index waits
|
|
6301
|
+
* for all of it: tables rebuilt from the log can be far behind, and a message's later events (an
|
|
6302
|
+
* edit, a reaction, a reply) come after its own index. Once caught up, each write applies as it lands.
|
|
6303
|
+
*/
|
|
6304
|
+
let whole = null;
|
|
6305
|
+
function caughtUp() {
|
|
6306
|
+
whole ??= session.consume(projection).then(() => void 0, (error) => {
|
|
6307
|
+
whole = null;
|
|
6308
|
+
throw error;
|
|
6309
|
+
});
|
|
6310
|
+
return whole;
|
|
6311
|
+
}
|
|
6312
|
+
/** `promise`, unless `signal` aborts first: the caller stops waiting, and what it waits for keeps going. */
|
|
6313
|
+
function untilAborted(promise, signal) {
|
|
6314
|
+
if (!signal) return promise;
|
|
6315
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
6316
|
+
return new Promise((resolve, reject) => {
|
|
6317
|
+
const abort = () => reject(signal.reason);
|
|
6318
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
6319
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
6320
|
+
});
|
|
6321
|
+
}
|
|
6322
|
+
/** Waits until the tables have applied `index`, or the whole log when it's omitted. */
|
|
6323
|
+
async function ensure(index, signal) {
|
|
6324
|
+
if (index !== void 0) await untilAborted(caughtUp(), signal);
|
|
6325
|
+
if (index !== void 0 && await tables.position() >= index) return;
|
|
6326
|
+
await session.consume(projection, {
|
|
6327
|
+
...index !== void 0 ? { through: index } : {},
|
|
6328
|
+
...signal ? { signal } : {}
|
|
6329
|
+
});
|
|
6330
|
+
}
|
|
5961
6331
|
return {
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
6332
|
+
tables,
|
|
6333
|
+
ensure,
|
|
6334
|
+
position: () => tables.position(),
|
|
6335
|
+
async message(id, signal) {
|
|
6336
|
+
await ensure(id, signal);
|
|
6337
|
+
return tables.message(id);
|
|
5967
6338
|
},
|
|
5968
|
-
|
|
6339
|
+
/** A thread's root and replies; `cursor` is the index the tables had applied before reading it. */
|
|
6340
|
+
async thread(root, signal) {
|
|
6341
|
+
await ensure(root, signal);
|
|
6342
|
+
const cursor = await tables.position();
|
|
6343
|
+
return {
|
|
6344
|
+
messages: await tables.thread(root),
|
|
6345
|
+
cursor
|
|
6346
|
+
};
|
|
6347
|
+
},
|
|
6348
|
+
async messagesAt(ids, index, signal) {
|
|
6349
|
+
await ensure(index, signal);
|
|
6350
|
+
return tables.messagesAt(ids, index);
|
|
6351
|
+
},
|
|
6352
|
+
/** By event ID, as of the whole log: an ID doesn't say how far to wait. */
|
|
6353
|
+
async byEventId(eventId, signal) {
|
|
6354
|
+
await ensure(void 0, signal);
|
|
6355
|
+
return tables.byEventId(eventId);
|
|
6356
|
+
},
|
|
6357
|
+
/** The reader of views of `messages`: what a link shows depends on where the message it points to lives. */
|
|
6358
|
+
reader: (access, messages) => readerOf(access, [...messages].flatMap((message) => linkedIds(message.links))),
|
|
6359
|
+
readerOf,
|
|
6360
|
+
async messages(filter, page) {
|
|
6361
|
+
catchUp();
|
|
6362
|
+
if (filter.channels?.length === 0) return {
|
|
6363
|
+
messages: [],
|
|
6364
|
+
position: await tables.position()
|
|
6365
|
+
};
|
|
6366
|
+
return tables.messages(filter, page);
|
|
6367
|
+
},
|
|
6368
|
+
async threads(filter, page) {
|
|
6369
|
+
catchUp();
|
|
6370
|
+
if (filter.channels?.length === 0) return {
|
|
6371
|
+
threads: [],
|
|
6372
|
+
position: await tables.position()
|
|
6373
|
+
};
|
|
6374
|
+
return tables.threads(filter, page);
|
|
6375
|
+
}
|
|
5969
6376
|
};
|
|
5970
6377
|
}
|
|
5971
|
-
/** The batch, only while `index` is still the session's last: A2's conditional append. */
|
|
5972
|
-
const appendIfLast = (session, index, events) => session.append.ifLastIndex(index, ...events);
|
|
5973
|
-
/** What A2 throws when the session's last index isn't the one a conditional append named. */
|
|
5974
|
-
const headMoved = (error) => error?.code === "LAST_INDEX_MISMATCH";
|
|
5975
6378
|
//#endregion
|
|
5976
6379
|
//#region src/server/registry.ts
|
|
5977
6380
|
/** A principal as a registration keeps it: enough to work out its access again at each match. */
|
|
@@ -6304,7 +6707,7 @@ function createSchedules(options) {
|
|
|
6304
6707
|
n
|
|
6305
6708
|
}
|
|
6306
6709
|
}, input);
|
|
6307
|
-
posted = indexOf(sent.id);
|
|
6710
|
+
posted = indexOf$1(sent.id);
|
|
6308
6711
|
} catch (error) {
|
|
6309
6712
|
if (!(error instanceof DroppedError)) throw error;
|
|
6310
6713
|
console.info(`[board] the middleware dropped schedule s${id}: ${error.message}`);
|
|
@@ -7276,13 +7679,13 @@ const SYNC_ACTOR = "board:sync";
|
|
|
7276
7679
|
const CLIENT_ACTOR = "board:client";
|
|
7277
7680
|
/** A cursor or message ref in a request, as this board's log index: decimals, from 0. */
|
|
7278
7681
|
function cursorAt(value) {
|
|
7279
|
-
const index = indexOf(value);
|
|
7682
|
+
const index = indexOf$1(value);
|
|
7280
7683
|
if (index === null) throw badRequest(`${value} isn't a cursor or a message ID on this board`, "invalid_cursor");
|
|
7281
7684
|
return index;
|
|
7282
7685
|
}
|
|
7283
7686
|
/** The message a ref in a request names, as its log index, or a 404 for one that names nothing here. */
|
|
7284
7687
|
function messageAt(value) {
|
|
7285
|
-
const index = indexOf(value);
|
|
7688
|
+
const index = indexOf$1(value);
|
|
7286
7689
|
if (index === null || index === 0) throw notFound(`message not found: #${value}`, "message_not_found");
|
|
7287
7690
|
return index;
|
|
7288
7691
|
}
|
|
@@ -7290,14 +7693,14 @@ function messageAt(value) {
|
|
|
7290
7693
|
* A reply's `after`, as the index of a message. One that isn't one is 0, which names no message:
|
|
7291
7694
|
* the post refuses it, after a retry that landed gets its reply back.
|
|
7292
7695
|
*/
|
|
7293
|
-
const afterAt = (value) => value === void 0 ? void 0 : indexOf(value) ?? 0;
|
|
7696
|
+
const afterAt = (value) => value === void 0 ? void 0 : indexOf$1(value) ?? 0;
|
|
7294
7697
|
/**
|
|
7295
7698
|
* A schedule's ID, `s12`, as its index in session `schedules`. `12` from a client that strips the
|
|
7296
7699
|
* `s`, and `ss12` from an older CLI that adds one to what this board hands out, name it too.
|
|
7297
7700
|
*/
|
|
7298
7701
|
function scheduleAt(value) {
|
|
7299
7702
|
const bare = value.replace(/^s{1,2}/, "");
|
|
7300
|
-
const index = indexOf(bare);
|
|
7703
|
+
const index = indexOf$1(bare);
|
|
7301
7704
|
if (index === null || index === 0) throw notFound(`schedule not found: s${bare}`, "schedule_not_found");
|
|
7302
7705
|
return index;
|
|
7303
7706
|
}
|
|
@@ -7504,7 +7907,9 @@ function build(options, binding) {
|
|
|
7504
7907
|
});
|
|
7505
7908
|
const access = createTrust({
|
|
7506
7909
|
store: log,
|
|
7507
|
-
accessNow: (principal) => binding.accessNow(principal)
|
|
7910
|
+
accessNow: (principal, grants) => binding.accessNow(principal, grants),
|
|
7911
|
+
explain: (principal, channel) => binding.explain(principal, channel),
|
|
7912
|
+
team: async () => (await binding.project()).teamId
|
|
7508
7913
|
});
|
|
7509
7914
|
const inboxes = inboxServer.session(INBOXES_SESSION);
|
|
7510
7915
|
/** The inboxes this instance knows have an `inbox.opened`, so most pushes write nothing more. */
|
|
@@ -7856,6 +8261,8 @@ function build(options, binding) {
|
|
|
7856
8261
|
},
|
|
7857
8262
|
grants: async (caller) => access.grants(await identityOf(caller)),
|
|
7858
8263
|
createGrant: async (caller, body) => access.createGrant(await identityOf(caller), body),
|
|
8264
|
+
updateGrant: async (caller, input) => access.updateGrant(await identityOf(caller), input),
|
|
8265
|
+
explain: async (caller, query) => access.explain(await identityOf(caller), query),
|
|
7859
8266
|
revokeGrant: async (caller, input) => access.revokeGrant(await identityOf(caller), input),
|
|
7860
8267
|
tokens: async (caller) => access.tokens(await identityOf(caller)),
|
|
7861
8268
|
createToken: async (caller, body) => access.createToken(await identityOf(caller), body),
|
|
@@ -8117,7 +8524,7 @@ function build(options, binding) {
|
|
|
8117
8524
|
return { message: await commit(write) };
|
|
8118
8525
|
}
|
|
8119
8526
|
if (body.origin === void 0 === (body.message === void 0)) throw badRequest("a change names its message by `origin` or by `message`, one or the other");
|
|
8120
|
-
const id = body.origin !== void 0 ? await locate(body.origin) : indexOf(body.message);
|
|
8527
|
+
const id = body.origin !== void 0 ? await locate(body.origin) : indexOf$1(body.message);
|
|
8121
8528
|
const found = id === null || id === 0 ? null : await reads.message(id);
|
|
8122
8529
|
if (!found || !may(found.channel)) return { message: null };
|
|
8123
8530
|
const authorized = (permission) => trusted.message(writes, permission, found.id);
|
|
@@ -8274,7 +8681,7 @@ function build(options, binding) {
|
|
|
8274
8681
|
async syncCopies(caller, query) {
|
|
8275
8682
|
const { principal } = await needSync(caller, "look up a sync");
|
|
8276
8683
|
await reads.ensure();
|
|
8277
|
-
const ids = [...new Set(query.message.map(indexOf).filter((id) => id !== null && id > 0))];
|
|
8684
|
+
const ids = [...new Set(query.message.map(indexOf$1).filter((id) => id !== null && id > 0))];
|
|
8278
8685
|
const everywhere = principal.access.everywhere("sync");
|
|
8279
8686
|
const [copies, messages] = await Promise.all([store.tables.copiesOf(ids), everywhere ? null : store.tables.messagesAt(ids, await store.tables.position())]);
|
|
8280
8687
|
const own = ownSync(caller);
|
|
@@ -8545,7 +8952,7 @@ function build(options, binding) {
|
|
|
8545
8952
|
if (!links) return void 0;
|
|
8546
8953
|
const { state: actors } = await session.state(actorsReducer);
|
|
8547
8954
|
return Promise.all(links.map(async ({ message: ref, ...link }) => {
|
|
8548
|
-
const id = ref === null ? null : indexOf(ref);
|
|
8955
|
+
const id = ref === null ? null : indexOf$1(ref);
|
|
8549
8956
|
const found = id === null || id === 0 ? null : await reads.message(id);
|
|
8550
8957
|
if (!found || found.deleted || !principal.access.readable(found.channel)) return {
|
|
8551
8958
|
...link,
|