@vercel/board 0.33.0 → 0.34.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.
Files changed (59) hide show
  1. package/dist/{access-N3XmkKXg.mjs → access-CdBcYPQH.mjs} +169 -12
  2. package/dist/access.d.mts +3 -3
  3. package/dist/access.mjs +5 -5
  4. package/dist/{actors-ihyN47OV.mjs → actors-MrIEr9LI.mjs} +2 -2
  5. package/dist/auth-DjoJygbG.mjs +599 -0
  6. package/dist/{auth-D6z3rMNj.d.mts → auth-aaoKt5DK.d.mts} +128 -9
  7. package/dist/backend-local.d.mts +1 -1
  8. package/dist/backend-local.mjs +1 -1
  9. package/dist/{backend-CWpyR1A7.d.mts → backend-u1sVvybh.d.mts} +30 -7
  10. package/dist/{chat-provider-DJpFUaFv.d.mts → chat-provider-De0iDnUB.d.mts} +2 -2
  11. package/dist/cli-commands.d.mts +1 -1
  12. package/dist/cli-commands.mjs +1 -1
  13. package/dist/cli-embedded.d.mts +2 -2
  14. package/dist/cli-embedded.mjs +1 -1
  15. package/dist/cli.mjs +5 -5
  16. package/dist/{commands-CHoMl06v.mjs → commands-B8oZEByR.mjs} +25 -51
  17. package/dist/{commands-BOBQHVqM.d.mts → commands-BkVMdXP1.d.mts} +0 -6
  18. package/dist/{conformance-qKmGLTAT.mjs → conformance-gqYBkXFS.mjs} +76 -83
  19. package/dist/conformance.d.mts +1 -1
  20. package/dist/conformance.mjs +1 -1
  21. package/dist/{engine-JxgZiikU.mjs → engine-rtOVWsiF.mjs} +2 -2
  22. package/dist/{errors-Pk0XV1hK.mjs → errors-D8ifv16L.mjs} +19 -4
  23. package/dist/{exports-gHDHlg0i.mjs → exports-Bx2dGpzr.mjs} +55 -10
  24. package/dist/exports-uwRl5qIj.d.mts +4 -0
  25. package/dist/{index-CXvvYNYj.d.mts → index-D6mK0Ial.d.mts} +2 -2
  26. package/dist/index.d.mts +6 -6
  27. package/dist/index.mjs +4 -4
  28. package/dist/index.node.d.mts +6 -6
  29. package/dist/index.node.mjs +3 -3
  30. package/dist/inspect/app.js +31 -31
  31. package/dist/{local-BbLjA5vI.mjs → local-CPz22MQ8.mjs} +1981 -1574
  32. package/dist/{main-CQpCZJFw.mjs → main-DScDKwQN.mjs} +45 -38
  33. package/dist/{middleware-BU7rVi9F.mjs → middleware-BjYpk4yq.mjs} +1 -1
  34. package/dist/provider-hB8QNrwm.d.mts +1031 -0
  35. package/dist/{provider-BlzUvcM9.d.mts → routes-De4W6lEs.d.mts} +2439 -2469
  36. package/dist/{serve-D8_W4UN6.mjs → serve-B1noQRkn.mjs} +4 -4
  37. package/dist/{server-BiIUXWbU.mjs → server-Ov6GBJ8j.mjs} +7 -7
  38. package/dist/{serving-D7rcUtSC.mjs → serving-2s7lqSBS.mjs} +1 -1
  39. package/dist/sync-chat-sdk.d.mts +2 -2
  40. package/dist/sync-github.d.mts +2 -2
  41. package/dist/sync-linear.d.mts +3 -2
  42. package/dist/sync-slack.d.mts +3 -3
  43. package/dist/sync.d.mts +2 -2
  44. package/dist/{targets-CknPGGVi.mjs → targets-aMdbp84G.mjs} +98 -10
  45. package/dist/{tokens-DPKjl3jf.mjs → tokens-LHLrnV_P.mjs} +2 -2
  46. package/docs/01-board/01-mounting.md +5 -3
  47. package/docs/01-board/03-identity.md +14 -13
  48. package/docs/01-board/07-schedules.md +1 -1
  49. package/docs/01-board/09-access.md +140 -59
  50. package/docs/03-guides/03-ci.md +15 -15
  51. package/docs/03-guides/05-agent-factory.md +5 -6
  52. package/docs/04-reference/01-cli.md +9 -16
  53. package/docs/04-reference/02-board.md +19 -8
  54. package/docs/04-reference/03-http.md +20 -13
  55. package/docs/04-reference/05-conformance.md +1 -1
  56. package/package.json +1 -1
  57. package/dist/auth-r-_PeZyw.mjs +0 -277
  58. package/dist/exports-BuKjVq2t.d.mts +0 -4
  59. package/dist/folds-DjFTiqIM.d.mts +0 -552
@@ -0,0 +1,599 @@
1
+ import { a as forbidden, l as unauthorized, r as badRequest, t as HttpError } from "./errors-D8ifv16L.mjs";
2
+ import { c as decide, o as combine, p as writtenCan, s as compileAccess, t as FULL_ACCESS, u as parseScope } from "./access-CdBcYPQH.mjs";
3
+ //#region src/server/grants.ts
4
+ /**
5
+ * How close `principal` is to the caller, or null when it doesn't name it: `principal` for its own
6
+ * user, project, repository's runs, issuer's claims, or app; `group` for every person, every
7
+ * project on the team in its environments, or every app on it; `everyone` for everyone.
8
+ */
9
+ function levelOf(principal, facts) {
10
+ const { caller } = facts;
11
+ switch (principal.kind) {
12
+ case "everyone": return "everyone";
13
+ case "all-users": return caller.kind === "user" && facts.member === true ? "group" : null;
14
+ case "user": return caller.kind === "user" && caller.userId === principal.userId ? "principal" : null;
15
+ case "all-projects": return caller.kind === "project" && facts.teamProject === true && principal.environments.includes(caller.environment) ? "group" : null;
16
+ case "project": return caller.kind === "project" && caller.projectId === principal.projectId && (principal.teamId === void 0 || caller.teamId === void 0 || caller.teamId === principal.teamId) && principal.environments.includes(caller.environment) ? "principal" : null;
17
+ case "github": {
18
+ if (caller.kind !== "github") return null;
19
+ const same = principal.repositoryId !== void 0 ? caller.repositoryId === principal.repositoryId : caller.repository === principal.repository;
20
+ const workflow = principal.workflow === void 0 || caller.ref !== void 0 && caller.workflowRef === `${caller.repository}/${principal.workflow}@${caller.ref}`;
21
+ const branch = principal.branch === void 0 || caller.ref === `refs/heads/${principal.branch}`;
22
+ const event = principal.event === void 0 || caller.event === principal.event;
23
+ return same && workflow && branch && event ? "principal" : null;
24
+ }
25
+ case "app": return caller.kind === "app" && caller.clientId === principal.clientId ? "principal" : null;
26
+ case "all-apps": return caller.kind === "app" && facts.teamApp === true ? "group" : null;
27
+ case "oidc": return caller.kind === "oidc" && caller.issuer === principal.issuer && Object.entries(principal.claims).every(([name, allowed]) => {
28
+ const value = caller.claims[name];
29
+ if (value === void 0) return false;
30
+ return typeof allowed === "string" ? String(value) === allowed : allowed.includes(String(value));
31
+ }) ? "principal" : null;
32
+ }
33
+ }
34
+ const RANK = {
35
+ principal: 0,
36
+ group: 1,
37
+ everyone: 2
38
+ };
39
+ /** The grants that name the caller, each as close as its closest principal; without `everyone`'s, when `own`. */
40
+ function matchedFor(facts, own = false) {
41
+ const matched = [];
42
+ for (const grant of facts.grants) {
43
+ let best = null;
44
+ for (const principal of grant.principals) {
45
+ if (own && principal.kind === "everyone") continue;
46
+ const level = levelOf(principal, facts);
47
+ if (level !== null && (best === null || RANK[level] < RANK[best])) best = level;
48
+ }
49
+ if (best !== null) matched.push({
50
+ level: best,
51
+ can: grant.can,
52
+ source: { grant }
53
+ });
54
+ }
55
+ return matched;
56
+ }
57
+ /** Whether anything but `everyone` lets the caller in: a grant, or, for a person, the team. */
58
+ function admits(facts, matched = matchedFor(facts)) {
59
+ if (facts.caller.kind === "user" && facts.member === true) return true;
60
+ return matched.some((found) => found.level !== "everyone");
61
+ }
62
+ /** `access`, capped and narrowed by its token. */
63
+ function limited(access, facts) {
64
+ let out = facts.cap === void 0 ? access : access.narrow({ "*": [...facts.cap] });
65
+ if (facts.can !== void 0) out = out.narrow(compileAccess(facts.can));
66
+ return out;
67
+ }
68
+ /**
69
+ * What the caller may do by the board's grants: `caller`, all of it, as `GET /me` says, and `own`,
70
+ * the same without `everyone`'s grants, what `checkGrantChange` judges reach by. At each channel the
71
+ * most specific pattern a grant naming it gives decides, then the closest principal there, and
72
+ * grants tied there add up; `cap` caps both, and a token's `can` narrows them. Null when
73
+ * nothing but `everyone` names it, since `everyone` lets no one in itself.
74
+ */
75
+ function grantAccess(facts) {
76
+ const matched = matchedFor(facts);
77
+ if (!admits(facts, matched)) return null;
78
+ return {
79
+ caller: limited(combine(matched), facts),
80
+ own: limited(combine(matchedFor(facts, true)), facts)
81
+ };
82
+ }
83
+ /** Which grants decide `channel` for the caller `facts` describes, from plain data, as a board explains it. */
84
+ function explainGrants(facts, channel) {
85
+ const matched = matchedFor(facts);
86
+ if (!admits(facts, matched)) return {
87
+ pattern: null,
88
+ over: [],
89
+ level: null,
90
+ grants: [],
91
+ capped: false,
92
+ permissions: []
93
+ };
94
+ const decision = decide(matched, channel);
95
+ const cap = facts.cap === void 0 ? null : compileAccess({ "*": [...facts.cap] });
96
+ const capped = cap ? decision.permissions.filter((permission) => cap.can(permission, channel)) : [...decision.permissions];
97
+ const token = facts.can === void 0 ? null : compileAccess(facts.can);
98
+ return {
99
+ pattern: decision.pattern,
100
+ over: [...decision.over],
101
+ level: decision.level,
102
+ grants: decision.sources.map((source) => source.grant),
103
+ capped: capped.length < decision.permissions.length,
104
+ permissions: token ? capped.filter((permission) => token.can(permission, channel)) : capped
105
+ };
106
+ }
107
+ //#endregion
108
+ //#region src/server/auth.ts
109
+ /**
110
+ * Whether a caller wrote what `by` says, as far as changing it goes (editing, deleting, canceling a
111
+ * schedule): its principal did, and when a board token pins the profile it writes as, as that
112
+ * profile. A token acts as its minter, so the principal alone would let one agent's token change
113
+ * what its minter or another agent wrote. Another token that pins the same profile writes as the
114
+ * same author, so a renewed one picks up where the last left off.
115
+ */
116
+ const wroteAs = (caller, by) => by.principal === caller.principal.id && ((caller.principal.pinned?.profile ?? null) === null || by.actor === caller.actor.id);
117
+ /**
118
+ * Principal IDs a board authenticates: its people, deployments, workflows, and its own code. No
119
+ * platform actor sync writes as may have one, or an import could pass for someone signed in.
120
+ */
121
+ const authenticates = (id) => /^(vercel|oidc|local|board):/.test(id) || id.startsWith("github:repo:");
122
+ const VERCEL_ISSUER = /^https:\/\/oidc\.vercel\.com(?:\/[a-z0-9-]+)?$/;
123
+ const GITHUB_ISSUER = "https://token.actions.githubusercontent.com";
124
+ /**
125
+ * `gitlab.com`, `example.com/oidc`, `ci.test%3A8443`: an issuer as a principal
126
+ * names it. A `:` (a port) and a `%` are percent-encoded, so the name has no `:`
127
+ * and the `sub` after it can hold anything. Issuers that differ only in what the
128
+ * URL normalizes (a trailing slash, the host's case) share a name, so the board
129
+ * refuses to trust two of them.
130
+ */
131
+ const issuerName = (iss) => {
132
+ const url = new URL(iss);
133
+ return `${url.host}${url.pathname.replace(/\/+$/, "")}`.replace(/[%:]/g, (char) => char === "%" ? "%25" : "%3A");
134
+ };
135
+ /** OIDC issuers to trust, checked: two that name the same principals can't both be. */
136
+ function trustedIssuers(issuers) {
137
+ const named = /* @__PURE__ */ new Map();
138
+ for (const iss of issuers) {
139
+ const name = issuerName(iss);
140
+ const other = named.get(name);
141
+ if (other !== void 0 && other !== iss) throw new Error(`oidc issuers ${other} and ${iss} name the same principals, oidc:${name}:<sub>: pin one of them`);
142
+ named.set(name, iss);
143
+ }
144
+ return new Set(issuers);
145
+ }
146
+ /** What a board token starts with, so board() knows its own before it tries any other verifier. */
147
+ const BOARD_TOKEN_PREFIX = "board_";
148
+ /**
149
+ * A board token's SHA-256, hex: what the board keeps instead of the secret, both when it mints one
150
+ * and when a request carries one. A token is 32 random bytes, so no salt or key is needed.
151
+ */
152
+ async function tokenHash(secret) {
153
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret)));
154
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
155
+ }
156
+ /**
157
+ * What a grant or a token left without `can` gives: what Vercel's API gives a project it lets use a
158
+ * board. Frozen all the way down: board reads it for every such grant, and @vercel/board/access
159
+ * exports it, so code that imports it can't widen them.
160
+ */
161
+ const DEFAULT_CAN = Object.freeze({ "*": Object.freeze([
162
+ "read",
163
+ "post",
164
+ "react",
165
+ "label"
166
+ ]) });
167
+ const GRANT_CLAIMS_MAX = 32;
168
+ const GRANT_VALUES_MAX = 32;
169
+ const GRANT_VALUE_MAX = 1e3;
170
+ const invalidGrant = (message) => badRequest(message, "invalid_grant");
171
+ /** Whether `host` names something on the board's own network rather than on the internet. */
172
+ function privateHost(host) {
173
+ const name = host.toLowerCase().replace(/\.$/, "");
174
+ if (name.startsWith("[") || /^\d+(\.\d+){3}$/.test(name) || /^\d+$/.test(name)) return true;
175
+ if (!name.includes(".") || name === "localhost") return true;
176
+ return /\.(localhost|local|internal|home|lan|corp|intranet)$/.test(name);
177
+ }
178
+ const GRANT_PRINCIPALS_MAX = 32;
179
+ /** The environments every Vercel project has: the only ones a grant for every project may name. */
180
+ const TEAM_ENVIRONMENTS = [
181
+ "production",
182
+ "preview",
183
+ "development"
184
+ ];
185
+ const PROJECT_ID = /^prj_[A-Za-z0-9]+$/;
186
+ const USER_ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,199}$/;
187
+ /** An app's client ID, as a board that verifies tokens itself takes it. */
188
+ const APP_ID = USER_ID;
189
+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
190
+ /** An OIDC issuer a grant may name: an https URL on the internet, not Vercel's or GitHub's, which have kinds of their own. */
191
+ function checkIssuer(issuer, trusted) {
192
+ let url;
193
+ try {
194
+ url = new URL(issuer);
195
+ } catch {
196
+ throw invalidGrant(`an oidc principal's issuer is an https URL, got ${issuer}`);
197
+ }
198
+ if (VERCEL_ISSUER.test(issuer)) throw invalidGrant("name Vercel's deployments as a project or all-projects, not as an oidc issuer");
199
+ if (issuer === "https://token.actions.githubusercontent.com") throw invalidGrant("name GitHub Actions runs as a github principal, not as an oidc issuer");
200
+ if (url.protocol !== "https:" || url.search || url.hash || url.username || url.password) throw invalidGrant(`an oidc principal's issuer is an https URL with no query or credentials, got ${issuer}`);
201
+ if (privateHost(url.hostname)) throw invalidGrant(`an oidc principal's issuer is on the internet, not ${url.hostname}`);
202
+ const name = issuerName(issuer);
203
+ const other = trusted.find((candidate) => candidate !== issuer && /^https:/.test(candidate) && issuerName(candidate) === name);
204
+ if (other !== void 0) throw invalidGrant(`issuers ${other} and ${issuer} name the same principals, oidc:${name}:<sub>: use ${other}`);
205
+ }
206
+ /** An issuer's claims, keys and lists sorted: at least one, since an issuer signs tokens for everyone it serves. */
207
+ function checkClaims(issuer, given) {
208
+ const entries = typeof given === "object" && given !== null ? Object.entries(given) : [];
209
+ if (entries.length === 0) throw invalidGrant(`name at least one claim for ${issuer}: its issuer signs tokens for everyone it serves`);
210
+ if (entries.length > GRANT_CLAIMS_MAX) throw invalidGrant(`an oidc principal names at most ${GRANT_CLAIMS_MAX} claims`);
211
+ const claims = {};
212
+ for (const [name, value] of entries.sort(([a], [b]) => a.localeCompare(b))) {
213
+ const values = typeof value === "string" ? [value] : Array.isArray(value) ? [...new Set(value)] : [];
214
+ if (values.length === 0 || values.some((one) => typeof one !== "string" || one === "")) throw invalidGrant(`claim ${name} has no value to match: give a string, or a list of them`);
215
+ if (values.length > GRANT_VALUES_MAX || values.some((one) => one.length > GRANT_VALUE_MAX)) throw invalidGrant(`claim ${name} lists at most ${GRANT_VALUES_MAX} values of up to ${GRANT_VALUE_MAX} characters`);
216
+ const sorted = values.sort();
217
+ claims[name] = sorted.length === 1 ? sorted[0] : sorted;
218
+ }
219
+ return claims;
220
+ }
221
+ /** Environments without repeats, in Vercel's order (production, preview, development), then custom ones by ID. */
222
+ const environmentsOf = (given) => {
223
+ const rank = (environment) => TEAM_ENVIRONMENTS.includes(environment) ? TEAM_ENVIRONMENTS.indexOf(environment) : TEAM_ENVIRONMENTS.length;
224
+ return [...new Set(given)].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
225
+ };
226
+ /** `ci.yml` is `.github/workflows/ci.yml`, as GitHub names a workflow in a token's `workflow_ref`. */
227
+ const workflowPath = (workflow) => workflow.includes("/") ? workflow : `.github/workflows/${workflow}`;
228
+ /**
229
+ * A principal as a board that verifies tokens itself keeps it, or a 400 `invalid_grant` that says
230
+ * what to write. Such a board has nothing to look a name up with, so it takes IDs: a user's ID, a
231
+ * project's `prj_…`, and a repository's `owner/name`, which it matches on the token's claims.
232
+ * `removal`: one to take out of a grant, which names a project without its environments. `team`: the
233
+ * board's own team, which a project it names is kept on, so it no longer matches once it's moved to
234
+ * another; null where the board doesn't know it, and then a project is its ID on any team.
235
+ */
236
+ function checkPrincipal(input, trusted, removal = false, team = null) {
237
+ switch (input.kind) {
238
+ case "user":
239
+ if (input.email !== void 0 && input.userId !== void 0) throw invalidGrant("a user is its email or its userId, not both");
240
+ if (input.email !== void 0) throw invalidGrant(`this board can't look up ${input.email}: it verifies tokens itself, so name the user by ID, { kind: 'user', userId }`);
241
+ if (input.userId === void 0 || !USER_ID.test(input.userId)) throw invalidGrant("a user is its userId, letters, numbers, and ._-");
242
+ return {
243
+ kind: "user",
244
+ userId: input.userId
245
+ };
246
+ case "project":
247
+ if (!PROJECT_ID.test(input.project)) throw invalidGrant(`this board can't look up the project ${input.project}: it verifies tokens itself, so name it by ID, prj_…`);
248
+ if (removal) return {
249
+ kind: "project",
250
+ projectId: input.project,
251
+ environments: []
252
+ };
253
+ if (input.environments === void 0) throw invalidGrant(`a project names the environments its deployments get in from, like ['production']`);
254
+ return {
255
+ kind: "project",
256
+ projectId: input.project,
257
+ environments: environmentsOf(input.environments),
258
+ ...team !== null ? { teamId: team } : {}
259
+ };
260
+ case "all-projects": {
261
+ if (removal) return {
262
+ kind: "all-projects",
263
+ environments: []
264
+ };
265
+ if (input.environments === void 0) throw invalidGrant(`all-projects names the environments its deployments get in from, like ['production']`);
266
+ const custom = input.environments.filter((environment) => !TEAM_ENVIRONMENTS.includes(environment));
267
+ if (custom.length > 0) throw invalidGrant(`all-projects names production, preview, or development: ${custom[0]} is one project's`);
268
+ return {
269
+ kind: "all-projects",
270
+ environments: environmentsOf(input.environments)
271
+ };
272
+ }
273
+ case "github":
274
+ if (!REPOSITORY.test(input.repository)) throw invalidGrant(`a github principal's repository is owner/name, got ${input.repository}`);
275
+ return {
276
+ kind: "github",
277
+ repository: input.repository,
278
+ ...input.workflow !== void 0 ? { workflow: workflowPath(input.workflow) } : {},
279
+ ...input.branch !== void 0 ? { branch: input.branch.replace(/^refs\/heads\//, "") } : {},
280
+ ...input.event !== void 0 ? { event: input.event } : {}
281
+ };
282
+ case "oidc":
283
+ checkIssuer(input.issuer, trusted);
284
+ return {
285
+ kind: "oidc",
286
+ issuer: input.issuer,
287
+ claims: checkClaims(input.issuer, input.claims)
288
+ };
289
+ case "app":
290
+ if (!APP_ID.test(input.app)) throw invalidGrant(`an app is its client ID, letters, numbers, and ._-, got ${input.app}`);
291
+ return {
292
+ kind: "app",
293
+ clientId: input.app
294
+ };
295
+ case "all-users":
296
+ case "all-apps":
297
+ case "everyone": return { kind: input.kind };
298
+ }
299
+ }
300
+ /** One principal's key: two that share it are the same principal. */
301
+ const principalKey = (principal) => JSON.stringify(principal);
302
+ /** Principals checked, without repeats, and a `can` kept as written: what a board that verifies tokens itself stores of a grant. */
303
+ function checkGrant(body, trusted, team = null) {
304
+ if (body.principals.length === 0) throw invalidGrant("a grant names at least one principal");
305
+ if (body.principals.length > GRANT_PRINCIPALS_MAX) throw invalidGrant(`a grant names at most ${GRANT_PRINCIPALS_MAX} principals`);
306
+ const seen = [...trusted];
307
+ const checked = body.principals.map((input) => {
308
+ const principal = checkPrincipal(input, seen, false, team);
309
+ if (principal.kind === "oidc") seen.push(principal.issuer);
310
+ return principal;
311
+ });
312
+ return {
313
+ principals: [...new Map(checked.map((principal) => [principalKey(principal), principal])).values()],
314
+ can: checkCan(body.can)
315
+ };
316
+ }
317
+ /** A grant's `can`, as written, or a 400 `invalid_grant`. */
318
+ function checkCan(can) {
319
+ try {
320
+ return writtenCan(can);
321
+ } catch (error) {
322
+ throw invalidGrant(error.message);
323
+ }
324
+ }
325
+ /**
326
+ * Whether `removal` takes `principal` out of a grant: the same user, project, or issuer and
327
+ * claims, whatever its environments; a repository's principals with the workflow, branch, and
328
+ * event it names, any of them where it names none; a group or everyone by its kind.
329
+ */
330
+ function removes(removal, principal) {
331
+ if (removal.kind !== principal.kind) return false;
332
+ switch (removal.kind) {
333
+ case "user": return removal.userId === principal.userId;
334
+ case "project": return removal.projectId === principal.projectId;
335
+ case "github": {
336
+ const other = principal;
337
+ return removal.repository === other.repository && (removal.workflow === void 0 || removal.workflow === other.workflow) && (removal.branch === void 0 || removal.branch === other.branch) && (removal.event === void 0 || removal.event === other.event);
338
+ }
339
+ case "oidc": {
340
+ const other = principal;
341
+ return removal.issuer === other.issuer && JSON.stringify(removal.claims) === JSON.stringify(other.claims);
342
+ }
343
+ case "app": return removal.clientId === principal.clientId;
344
+ default: return true;
345
+ }
346
+ }
347
+ /**
348
+ * `added` joined into `principal` when it's the same principal, as a removal would find it: a
349
+ * project's environments, or every project's, together. Null when it's another principal. Adding
350
+ * never narrows what a grant names; a remove and an add in one update do.
351
+ */
352
+ function joined(added, principal) {
353
+ if (added.kind !== principal.kind) return null;
354
+ if (added.kind === "project" || added.kind === "all-projects") {
355
+ const other = principal;
356
+ if (added.kind === "project" && added.projectId !== other.projectId) return null;
357
+ return {
358
+ ...other,
359
+ environments: environmentsOf([...other.environments, ...added.environments])
360
+ };
361
+ }
362
+ return principalKey(added) === principalKey(principal) ? principal : null;
363
+ }
364
+ /** A person's user ID: `vercel:user:u_123` is `u_123`, and a local board's `local:user:jb` is `jb`. */
365
+ const userIdOf = (id) => id.split(":").slice(2).join(":");
366
+ /**
367
+ * A verified principal as `grantAccess` takes it: who it is in grants' terms, and what the board
368
+ * knows of its team. A person on a board that lets them in is on its team; a deployment's project
369
+ * is when its token's `owner_id` is the board's `team`. Null for one no grant names, such as the
370
+ * board's own code.
371
+ */
372
+ function callerFacts(principal, facts, team) {
373
+ const claims = facts?.claims ?? {};
374
+ if (principal.kind === "person") return {
375
+ caller: {
376
+ kind: "user",
377
+ userId: userIdOf(principal.id)
378
+ },
379
+ member: true
380
+ };
381
+ if (facts?.issuer === "vercel") return {
382
+ caller: {
383
+ kind: "project",
384
+ projectId: String(claims.project_id ?? ""),
385
+ environment: String(claims.environment ?? ""),
386
+ ...typeof claims.owner_id === "string" ? { teamId: claims.owner_id } : {}
387
+ },
388
+ teamProject: team !== null && claims.owner_id === team
389
+ };
390
+ if (facts?.issuer === "github") return { caller: {
391
+ kind: "github",
392
+ repository: String(claims.repository ?? ""),
393
+ ...claims.repository_id !== void 0 ? { repositoryId: String(claims.repository_id) } : {},
394
+ ...claims.workflow_ref !== void 0 ? { workflowRef: String(claims.workflow_ref) } : {},
395
+ ...claims.ref !== void 0 ? { ref: String(claims.ref) } : {},
396
+ ...claims.event_name !== void 0 ? { event: String(claims.event_name) } : {}
397
+ } };
398
+ if (facts?.issuer === "oidc") return { caller: {
399
+ kind: "oidc",
400
+ issuer: facts.iss,
401
+ claims
402
+ } };
403
+ return null;
404
+ }
405
+ /**
406
+ * The issuers a verifier trusts for grants, beside its own: a grant's issuer only while it's an
407
+ * https URL on the internet and names principals no issuer before it does. A board refuses any
408
+ * other when it's granted; one stored before it did is never asked for keys, and never breaks the
409
+ * verifier for everyone else.
410
+ */
411
+ function verifiedIssuers(base, granted) {
412
+ const taken = new Set(base.map(issuerName));
413
+ const issuers = [...base];
414
+ for (const issuer of granted) {
415
+ if (base.includes(issuer)) continue;
416
+ const url = URL.parse(issuer);
417
+ if (url?.protocol !== "https:" || privateHost(url.hostname)) continue;
418
+ const name = issuerName(issuer);
419
+ if (taken.has(name)) continue;
420
+ taken.add(name);
421
+ issuers.push(issuer);
422
+ }
423
+ return issuers;
424
+ }
425
+ /** The OIDC issuers grants name: their tokens are verified too. */
426
+ const grantIssuers = (grants) => [...new Set(grants.flatMap((grant) => grant.principals.flatMap((principal) => principal.kind === "oidc" ? [principal.issuer] : [])))];
427
+ /** A token no grant lets in, and the grant that would. */
428
+ const notGranted = (who, grant) => new HttpError(403, "forbidden", `this token can't use this board: no grant lets in ${who}`, { hint: `Grant it: vb grants create ${grant}` });
429
+ /**
430
+ * What principals may do, by the board's grants, as `grantAccess` decides: at each channel, the
431
+ * most specific pattern decides, then the closest principal, and ties add up. People are always
432
+ * let in, and the board's own deployments in its environment may do everything.
433
+ */
434
+ function createAuthority(options) {
435
+ /** What `grantAccess` decides `principal` from: the grants of `snapshot`, when given, or as they are now. Null facts for one no grant names. */
436
+ async function factsFor(principal, facts, team, snapshot) {
437
+ const grants = snapshot ?? (options.grants ? await options.grants() : []);
438
+ const known = callerFacts(principal, facts, team);
439
+ return {
440
+ grants,
441
+ facts: known ? {
442
+ ...known,
443
+ grants
444
+ } : null
445
+ };
446
+ }
447
+ /**
448
+ * What decides a principal that isn't a person: everything for the board's own deployments in
449
+ * its environment, and for anyone else, the grants that name it. `everyone` lets no one in: a
450
+ * 401 or 403 that says which grant would, when nothing else names it.
451
+ */
452
+ async function byGrants(principal, facts, snapshot) {
453
+ const claims = facts?.claims ?? {};
454
+ const own = facts?.issuer === "vercel" ? await options.project() : null;
455
+ const environment = String(claims.environment ?? "");
456
+ const here = boardEnvironment();
457
+ const ownDeployment = own !== null && own.id !== null && claims.project_id === own.id;
458
+ if (ownDeployment && here !== null && environment === here) return { fixed: FULL_ACCESS };
459
+ if (!facts) throw forbidden("this token can't use this board");
460
+ const { grants, facts: found } = await factsFor(principal, facts, own?.teamId ?? null, snapshot);
461
+ if (found && admits(found)) return { facts: found };
462
+ if (facts.issuer === "oidc" && !grantIssuers(grants).includes(facts.iss)) throw unauthorized(`untrusted issuer: ${facts.iss}`);
463
+ if (facts.issuer === "oidc") throw forbidden("this token can't use this board: no grant lets in its claims");
464
+ if (facts.issuer === "github") {
465
+ const repository = String(claims.repository ?? "");
466
+ throw notGranted(repository || "its repository", `--github ${repository || "<OWNER/REPO>"}`);
467
+ }
468
+ const project = String(claims.project_id ?? "") || "<PROJECT_ID>";
469
+ const grant = `--project ${project} --environment ${environment || "<ENVIRONMENT>"}`;
470
+ if (ownDeployment) throw new HttpError(403, "forbidden", `this token can't use this board: it runs in ${here ?? "no Vercel environment"}, and its ${environment || "unnamed"} deployments need a grant`, { hint: `Grant them: vb grants create ${grant}` });
471
+ throw notGranted(`project ${project} in ${environment || "no environment"}`, grant);
472
+ }
473
+ /**
474
+ * What decides a principal's access, before its scope narrows it: the board's own code and the
475
+ * platform users sync writes as may do everything; a person is always let in, with what the
476
+ * grants that name them give (everything, where the board keeps no grants); anyone else as
477
+ * `byGrants` says. A host's principal is what its kind is, until it expires. A 401 or 403 when
478
+ * it may do nothing.
479
+ */
480
+ async function resolve(principal, snapshot) {
481
+ const hosted = principal.facts?.issuer === "host";
482
+ if (principal.id.startsWith("board:") || principal.kind === "external" && !hosted) return { fixed: FULL_ACCESS };
483
+ if (hosted) {
484
+ if (!options.hosts) throw forbidden("this token can't use this board: its board no longer takes a host's principals");
485
+ const { exp } = principal.facts.claims;
486
+ if (typeof exp === "number" && exp * 1e3 <= Date.now()) throw unauthorized("token expired");
487
+ }
488
+ if (principal.kind === "person") {
489
+ if (!options.grants) return { fixed: FULL_ACCESS };
490
+ const { facts } = await factsFor(principal, null, null, snapshot);
491
+ return { facts };
492
+ }
493
+ return byGrants(principal, (hosted ? void 0 : principal.facts) ?? factsFromId(principal.id), snapshot);
494
+ }
495
+ /**
496
+ * What a principal may do now, narrowed by its scope, or under `snapshot`, grants as a write is
497
+ * about to change them. A 401 or 403 when it may do nothing.
498
+ */
499
+ async function grant(principal, snapshot) {
500
+ const resolved = await resolve(principal, snapshot);
501
+ const scope = principal.scope === void 0 ? void 0 : parseScope(principal.scope);
502
+ if ("fixed" in resolved) return scope === void 0 ? resolved.fixed : resolved.fixed.narrow(scope);
503
+ const decided = grantAccess({
504
+ ...resolved.facts,
505
+ ...scope !== void 0 ? { can: scope } : {}
506
+ });
507
+ if (!decided) throw forbidden("this token can't use this board");
508
+ return decided.caller;
509
+ }
510
+ /** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing. */
511
+ async function accessNow(principal, snapshot) {
512
+ try {
513
+ return await grant(principal, snapshot);
514
+ } catch (error) {
515
+ const status = error.status;
516
+ if (status === 401 || status === 403) return null;
517
+ throw error;
518
+ }
519
+ }
520
+ return {
521
+ grant,
522
+ accessNow,
523
+ resolve
524
+ };
525
+ }
526
+ /**
527
+ * The Vercel environment the board runs in: `production`, `preview`, or a
528
+ * custom environment's name. `VERCEL_TARGET_ENV` names custom environments,
529
+ * where `VERCEL_ENV` says `preview`. Null outside Vercel, where only people
530
+ * get in without a grant.
531
+ */
532
+ const boardEnvironment = () => process.env.VERCEL_TARGET_ENV || process.env.VERCEL_ENV || null;
533
+ /**
534
+ * What a principal's ID still says, for one stored before the board kept
535
+ * claims: a deployment's project ID and environment. A workflow's ID names
536
+ * neither its repository nor its run, so it says nothing, and a grant that
537
+ * needs more than the ID no longer matches.
538
+ */
539
+ function factsFromId(id) {
540
+ const deployment = id.match(/^vercel:project:([^:]+):([^:]+)$/);
541
+ return deployment ? {
542
+ issuer: "vercel",
543
+ iss: "",
544
+ claims: {
545
+ project_id: deployment[1],
546
+ environment: deployment[2]
547
+ }
548
+ } : null;
549
+ }
550
+ /** What marks `oidcTokens()`, so board() can tell it makes no host's principals. */
551
+ const TOKENS = Symbol("board.oidcTokens");
552
+ /** The principals `oidcTokens()` made: board() takes them as they are, and checks the rest as a host's. */
553
+ const verifiedTokens = /* @__PURE__ */ new WeakSet();
554
+ /** Marks a principal `oidcTokens()` made. */
555
+ function markVerified(principal) {
556
+ verifiedTokens.add(principal);
557
+ return principal;
558
+ }
559
+ /** Whether `authenticate` is `oidcTokens()`'s alone: it makes no host's principals. */
560
+ const verifiesTokens = (authenticate) => TOKENS in authenticate;
561
+ /** Whether `oidcTokens()` made `principal`, as opposed to a host's own verifier. */
562
+ const fromTokens = (principal) => verifiedTokens.has(principal);
563
+ const PRINCIPAL_ID = /^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[^\s+\]]{1,200}$/;
564
+ const KINDS = [
565
+ "person",
566
+ "deployment",
567
+ "workflow",
568
+ "external"
569
+ ];
570
+ /**
571
+ * Checks what a host's own verifier returned. A malformed principal is the host's bug, so it
572
+ * fails the request rather than letting a half-identity write.
573
+ */
574
+ function hostPrincipal(value) {
575
+ const fail = (why) => {
576
+ throw new TypeError(`authenticate returned an invalid principal: ${why}`);
577
+ };
578
+ if (typeof value !== "object" || value === null) fail("not an object");
579
+ if (typeof value.id !== "string" || !PRINCIPAL_ID.test(value.id) || value.id.startsWith("board:")) fail(`id must look like \`vercel:user:<id>\`, got ${JSON.stringify(value.id)}`);
580
+ if (!KINDS.includes(value.kind)) fail(`kind must be one of ${KINDS.join(", ")}`);
581
+ if (typeof value.handle !== "string" || !/^\S{1,64}$/.test(value.handle)) fail("handle must be 1-64 characters, no spaces");
582
+ const expiresAt = value.expiresAt ?? null;
583
+ if (expiresAt !== null && (!(expiresAt instanceof Date) || Number.isNaN(expiresAt.getTime()))) fail("expiresAt must be a Date or null");
584
+ if (expiresAt !== null && expiresAt.getTime() <= Date.now()) throw unauthorized("token expired");
585
+ const claims = expiresAt === null ? {} : { exp: Math.floor(expiresAt.getTime() / 1e3) };
586
+ return {
587
+ id: value.id,
588
+ kind: value.kind,
589
+ handle: value.handle,
590
+ expiresAt,
591
+ facts: {
592
+ issuer: "host",
593
+ iss: "",
594
+ claims
595
+ }
596
+ };
597
+ }
598
+ //#endregion
599
+ export { workflowPath as C, grantAccess as E, verifiesTokens as S, explainGrants as T, privateHost as _, VERCEL_ISSUER as a, trustedIssuers as b, checkGrant as c, fromTokens as d, grantIssuers as f, markVerified as g, joined as h, TOKENS as i, checkPrincipal as l, issuerName as m, DEFAULT_CAN as n, authenticates as o, hostPrincipal as p, GITHUB_ISSUER as r, checkCan as s, BOARD_TOKEN_PREFIX as t, createAuthority as u, removes as v, wroteAs as w, verifiedIssuers as x, tokenHash as y };