@mediamonks/canopy-cli 0.7.51 → 0.7.53

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 (75) hide show
  1. package/dist/{ai-BjnuSjmw.mjs → ai-BlqO9NhM.mjs} +2 -2
  2. package/dist/{api-DmJrIsE7.mjs → api-D4KUT6Ly.mjs} +9 -8
  3. package/dist/{audience-BSvOEbco.mjs → audience-Dlrsdthb.mjs} +3 -3
  4. package/dist/{browse-BPLWhoFI.mjs → browse-CW3CnhK_.mjs} +2 -2
  5. package/dist/{calls-COIxX32d.mjs → calls-DFtWVJfv.mjs} +3 -3
  6. package/dist/{db-D5SXZrp5.mjs → db-Dy1csI71.mjs} +15 -18
  7. package/dist/{deploy-D8OZyhH8.mjs → deploy-DHjZj2Pq.mjs} +13 -19
  8. package/dist/dev-CVC7elOr.mjs +2 -0
  9. package/dist/{dev-DjK3Y8jb.mjs → dev-L5slb6ke.mjs} +10 -9
  10. package/dist/{dev-worker-CDxgu7c1.mjs → dev-worker-DBBN0F6X.mjs} +15 -33
  11. package/dist/docs/access-tokens.md +145 -0
  12. package/dist/docs/ci.md +8 -0
  13. package/dist/docs/cli-dev.md +1 -1
  14. package/dist/docs/cli-schedule.md +1 -1
  15. package/dist/docs/cli-token.md +1 -1
  16. package/dist/docs/developers-architecture.md +16 -5
  17. package/dist/docs/index.json +10 -0
  18. package/dist/docs/outside-sign-in.md +1 -1
  19. package/dist/docs/overview-faq.md +4 -3
  20. package/dist/docs/platform-client-access.md +1 -1
  21. package/dist/docs/platform-credentials.md +76 -0
  22. package/dist/docs/platform-egress.md +4 -4
  23. package/dist/docs/platform-members-and-access.md +31 -6
  24. package/dist/docs/platform-project-data.md +4 -0
  25. package/dist/docs/platform-schedules.md +4 -4
  26. package/dist/docs/porting-nextjs.md +23 -23
  27. package/dist/docs/sdk-auth.md +61 -14
  28. package/dist/docs/sdk-files.md +117 -4
  29. package/dist/docs/sdk.md +17 -10
  30. package/dist/docs/staging.md +1 -1
  31. package/dist/docs/static-serving.md +6 -3
  32. package/dist/docs/troubleshooting.md +21 -1
  33. package/dist/{docs-CLgKBi8H.mjs → docs-bnQLqEOn.mjs} +4 -4
  34. package/dist/{egress-BoGWBHRa.mjs → egress-hKpsJF84.mjs} +4 -10
  35. package/dist/{feedback-B6tqJ3cd.mjs → feedback-vHJwLyWF.mjs} +4 -4
  36. package/dist/{files-B7toJRlj.mjs → files-DKtyMjY0.mjs} +3 -3
  37. package/dist/index.mjs +39 -52
  38. package/dist/{local-BmUmiOUN.mjs → local-B15wYk6z.mjs} +19 -8
  39. package/dist/{login-DrMr99-A.mjs → login-cbwynFoT.mjs} +3 -3
  40. package/dist/{logs-DJWrL6ja.mjs → logs-ByDPHO28.mjs} +3 -3
  41. package/dist/{mcp-CWtqUFE3.mjs → mcp-BmT4Es_B.mjs} +3 -3
  42. package/dist/{migrations-BReMlGWP.mjs → migrations-k5pyUUR0.mjs} +3 -3
  43. package/dist/{open-6ev_6m0p.mjs → open-CYfkeTaw.mjs} +2 -2
  44. package/dist/{package-4SGn0Cy3.mjs → package-DtU4jB_Z.mjs} +1 -1
  45. package/dist/{project-template-Bas1UN2O.mjs → project-template-B297eCQ0.mjs} +3 -3
  46. package/dist/project-template-B6YpesjZ.mjs +2 -0
  47. package/dist/{projects-BEBYhy6k.mjs → projects-ztlDQi0P.mjs} +28 -28
  48. package/dist/{rename-PIJmdzHk.mjs → rename-BZ8hvUUt.mjs} +3 -3
  49. package/dist/{repo-Dry87b9d.mjs → repo-BUIM4d_1.mjs} +4 -10
  50. package/dist/repo-fDD4TcJ4.mjs +2 -0
  51. package/dist/{roles-CXY226VM.mjs → roles-DvywfJ8x.mjs} +1 -1
  52. package/dist/{roles-CUFRTp_R.mjs → roles-Yn8U3cr-.mjs} +3 -3
  53. package/dist/{schedule-DJsclUxC.mjs → schedule-Cv26MIfS.mjs} +3 -3
  54. package/dist/{secrets-CV2IwVwU.mjs → secrets-C6tF7BI9.mjs} +3 -3
  55. package/dist/{site-BL5Ik-yj.mjs → site-C0nf9RXY.mjs} +8 -3
  56. package/dist/skill/canopy/SKILL.md +9 -1
  57. package/dist/{skill-CY_4eqOD.mjs → skill-CRTV3ZQ1.mjs} +2 -2
  58. package/dist/{src-DbqT3K2l.mjs → src-UBUAqzqH.mjs} +419 -41
  59. package/dist/{staging-B9sjqvfh.mjs → staging-C9mn0EBS.mjs} +6 -14
  60. package/dist/templates/spa/AGENTS.md +3 -3
  61. package/dist/templates/spa/README.md +2 -2
  62. package/dist/templates/spa/package.json +1 -1
  63. package/dist/templates/static/AGENTS.md +3 -3
  64. package/dist/templates/static/README.md +2 -2
  65. package/dist/templates/worker/AGENTS.md +3 -3
  66. package/dist/templates/worker/README.md +2 -2
  67. package/dist/templates/worker/package.json +1 -1
  68. package/dist/{token-BT2_ELX6.mjs → token-DIJtUPrE.mjs} +3 -3
  69. package/dist/{ui-Ddw4d2Nn.mjs → ui-BPq6-hKS.mjs} +16 -3
  70. package/dist/{upgrade-Dxzb3e3r.mjs → upgrade-LTEfQn4L.mjs} +2 -2
  71. package/dist/{usage-VMT75MZ4.mjs → usage-DBhL6SUo.mjs} +3 -3
  72. package/package.json +3 -3
  73. package/dist/dev-DkaQjBTp.mjs +0 -2
  74. package/dist/project-template-Dti_Mmnb.mjs +0 -2
  75. package/dist/repo-CGTFmIWM.mjs +0 -2
@@ -1,6 +1,6 @@
1
- import { d as resolveProject, l as projectFlagArgs } from "./site-BL5Ik-yj.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-DmJrIsE7.mjs";
3
- import { r as reportErrors, t as formatDateTime } from "./ui-Ddw4d2Nn.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-C0nf9RXY.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-D4KUT6Ly.mjs";
3
+ import { i as reportErrors, n as formatDateTime } from "./ui-BPq6-hKS.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/schedule.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { c as projectDirArgs, d as resolveProject } from "./site-BL5Ik-yj.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-DmJrIsE7.mjs";
3
- import { o as unwrap, r as reportErrors, t as formatDateTime } from "./ui-Ddw4d2Nn.mjs";
1
+ import { f as resolveProject, l as projectDirArgs } from "./site-C0nf9RXY.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-D4KUT6Ly.mjs";
3
+ import { i as reportErrors, n as formatDateTime, s as unwrap } from "./ui-BPq6-hKS.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/secrets.ts
@@ -121,8 +121,8 @@ function resolveConfig(opts = {}) {
121
121
  projectDomain,
122
122
  projectProtocol,
123
123
  cloud: baked?.cloud,
124
- issuer: process.env["CANOPY_OIDC_ISSUER"] ?? file.issuer ?? DEFAULT_ISSUER,
125
- cliClientId: process.env["CANOPY_OIDC_CLIENT_ID"] ?? file.cliClientId ?? DEFAULT_CLI_CLIENT_ID,
124
+ issuer: process.env["CANOPY_OIDC_ISSUER"] ?? file.issuer ?? "https://s4capital.onelogin.com/oidc/2",
125
+ cliClientId: process.env["CANOPY_OIDC_CLIENT_ID"] ?? file.cliClientId ?? "b69755d0-6678-013f-b5ce-09fe44a57aa0180501",
126
126
  token: auth?.token,
127
127
  tokenExpiresAt: auth?.tokenExpiresAt,
128
128
  email: auth?.email,
@@ -259,6 +259,11 @@ function tryResolveProject(args) {
259
259
  slug: args.project ?? tryReadCanopyJson(dir)?.slug
260
260
  };
261
261
  }
262
+ /** A deploy version argument (`3` or `v3`) as a number; anything else throws. */
263
+ function parseVersionArg(raw) {
264
+ if (!/^v?\d+$/.test(raw)) throw new Error(`Invalid version "${raw}" — expected a number like 3 or v3.`);
265
+ return Number(raw.replace(/^v/, ""));
266
+ }
262
267
  const GITHUB_HOST = /^(?:github\.com|[a-z0-9][a-z0-9-]*\.ghe\.com)$/;
263
268
  /**
264
269
  * The GitHub repository a git remote URL points at, or null when it is not on
@@ -349,4 +354,4 @@ function siteHeaderLine(cliVersion) {
349
354
  return `canopy ${cliVersion} · ${c.envOverride || !c.profileId ? c.apiUrl : `${c.profileId} (${c.projectDomain ?? new URL(c.apiUrl).hostname})`}`;
350
355
  }
351
356
  //#endregion
352
- export { isProfileId as C, getBakedProfile as S, listBakedProfiles as _, parseGithubRemote as a, upsertProfileAuth as b, projectDirArgs as c, resolveProject as d, rewriteCanopyJsonSlug as f, clearAllProfileTokens as g, tryResolveProject as h, siteHeaderLine as i, projectFlagArgs as l, tryReadCanopyJson as m, setInvocationProfile as n, parseRepositoryArg as o, stagingUrl as p, siteConfig as r, projectDialect as s, projectDir as t, projectUrl as u, readConfigFile as v, writeConfigFile as x, setActiveProfile as y };
357
+ export { upsertProfileAuth as C, isProfileId as E, setActiveProfile as S, getBakedProfile as T, DEFAULT_CLI_CLIENT_ID as _, parseGithubRemote as a, listBakedProfiles as b, projectDialect as c, projectUrl as d, resolveProject as f, tryResolveProject as g, tryReadCanopyJson as h, siteHeaderLine as i, projectDirArgs as l, stagingUrl as m, setInvocationProfile as n, parseRepositoryArg as o, rewriteCanopyJsonSlug as p, siteConfig as r, parseVersionArg as s, projectDir as t, projectFlagArgs as u, DEFAULT_ISSUER as v, writeConfigFile as w, readConfigFile as x, clearAllProfileTokens as y };
@@ -118,7 +118,15 @@ and never go stale.
118
118
  only some roles may see in `private_` tables. Try other roles locally with
119
119
  `canopy dev --as-role <slug>`. Adding or removing people is the owner's call
120
120
  (`canopy members add|remove`) — confirm with the user first.
121
- - CI credentials: `canopy token create | list | revoke`
121
+ - Credentials (`canopy docs platform-credentials`): CI **deploys** use a linked
122
+ repository (`canopy repo link`, GitHub) or a deploy token (`canopy token
123
+ create | list | revoke`). Software that **calls the project's `/api`** — a
124
+ CI job, script, plugin or desktop app — uses an access token the owner
125
+ enables and makes in the dashboard (project key, or a person's personal
126
+ token; `canopy docs access-tokens`). The backend reads it on
127
+ `env.CALLER.token` and checks the project's scopes with `requireScope`; give
128
+ every `switch (env.CALLER.kind)` a refusing `default`. Never put any token in
129
+ the repository.
122
130
  - Git: `canopy repo show --json` (is there a repository, and its remote) ·
123
131
  `canopy repo create` · `canopy repo clone <slug>` · `canopy repo connect`
124
132
  (set up an existing folder). Then plain `git`: the CLI gives git
@@ -1,5 +1,5 @@
1
- import { t as version } from "./package-4SGn0Cy3.mjs";
2
- import { r as reportErrors } from "./ui-Ddw4d2Nn.mjs";
1
+ import { t as version } from "./package-DtU4jB_Z.mjs";
2
+ import { i as reportErrors } from "./ui-BPq6-hKS.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  import { cpSync, existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
@@ -49,6 +49,16 @@ function blobServingHeaders(contentType, key) {
49
49
  return headers;
50
50
  }
51
51
  //#endregion
52
+ //#region ../data-plane/src/store.ts
53
+ /** The put condition for "only if nothing is stored under this key yet" (R2's own form). */
54
+ function createOnly() {
55
+ return new Headers({ "if-none-match": "*" });
56
+ }
57
+ /** Whether a put asked for createOnly(). */
58
+ function isCreateOnly(onlyIf) {
59
+ return onlyIf?.get("if-none-match")?.trim() === "*";
60
+ }
61
+ //#endregion
52
62
  //#region ../data-plane/src/blob.ts
53
63
  /**
54
64
  * /blob — the SDK's file storage over an injectable BlobStore (a bucket
@@ -60,7 +70,14 @@ function blobServingHeaders(contentType, key) {
60
70
  * mints download URLs via the injected signer — verification lives with the
61
71
  * host's auth middleware (see signing.ts).
62
72
  */
63
- const MAX_BLOB_BYTES = 25 * 1024 * 1024;
73
+ /**
74
+ * Up to this size an upload is read into memory before it is stored, which
75
+ * every host and every project runtime can take. Above it the body streams
76
+ * to the bucket, so it must declare its length (blob-file-limits).
77
+ */
78
+ const BUFFERED_BLOB_BYTES = 25 * 1024 * 1024;
79
+ /** The per-file limit where uploads stream end to end (Cloudflare sites, the local sandbox). */
80
+ const STREAMED_BLOB_BYTES = 200 * 1024 * 1024;
64
81
  const MAX_LIST_KEYS = 1e3;
65
82
  /** Lifetime of a download URL when the caller doesn't ask for one. */
66
83
  const DEFAULT_URL_TTL_SECONDS = 600;
@@ -70,6 +87,46 @@ const DEFAULT_URL_TTL_SECONDS = 600;
70
87
  * long that window can be, however large an `expiresIn` a project passes.
71
88
  */
72
89
  const MAX_URL_TTL_SECONDS = 1440 * 60;
90
+ /** Lifetime of an upload link when the caller doesn't ask for one. */
91
+ const DEFAULT_UPLOAD_TTL_SECONDS = 600;
92
+ /** An upload link writes, so its window is shorter than a download's. */
93
+ const MAX_UPLOAD_TTL_SECONDS = 3600;
94
+ /** A media type the way a Content-Type header carries it, without parameters. */
95
+ const MEDIA_TYPE_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/i;
96
+ /** The media type of a Content-Type header, lower-cased, parameters dropped. */
97
+ function mediaType(header) {
98
+ return (header ?? "").split(";")[0].trim().toLowerCase();
99
+ }
100
+ /** The mint request's options, or the field that is wrong. */
101
+ function uploadUrlOptions(body, limit) {
102
+ const o = body && typeof body === "object" ? body : {};
103
+ const expiresIn = o["expiresIn"] ?? DEFAULT_UPLOAD_TTL_SECONDS;
104
+ if (typeof expiresIn !== "number" || !Number.isInteger(expiresIn) || expiresIn < 1) return {
105
+ error: "invalid_expires_in",
106
+ detail: "expiresIn must be a whole number of seconds above zero"
107
+ };
108
+ const maxBytes = o["maxBytes"] ?? limit;
109
+ if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < 1) return {
110
+ error: "invalid_max_bytes",
111
+ detail: "maxBytes must be a whole number of bytes above zero"
112
+ };
113
+ const contentType = o["contentType"] ?? null;
114
+ if (contentType !== null && (typeof contentType !== "string" || !MEDIA_TYPE_RE.test(contentType))) return {
115
+ error: "invalid_content_type",
116
+ detail: "contentType must be a media type such as image/png"
117
+ };
118
+ const overwrite = o["overwrite"] ?? false;
119
+ if (typeof overwrite !== "boolean") return {
120
+ error: "invalid_overwrite",
121
+ detail: "overwrite must be true or false"
122
+ };
123
+ return {
124
+ expiresIn: Math.min(expiresIn, MAX_UPLOAD_TTL_SECONDS),
125
+ maxBytes: Math.min(maxBytes, limit),
126
+ contentType: contentType === null ? null : contentType.toLowerCase(),
127
+ overwrite
128
+ };
129
+ }
73
130
  /**
74
131
  * Requested lifetime in seconds, clamped to the platform ceiling. `null` marks
75
132
  * a value we refuse to guess at (non-numeric, zero, negative) so the caller
@@ -88,8 +145,56 @@ function safeBlobKey(raw) {
88
145
  if (raw.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) return null;
89
146
  return raw;
90
147
  }
148
+ /**
149
+ * An upload's body, within `maxBytes` (null when over). Up to
150
+ * BUFFERED_BLOB_BYTES it is read into memory, as every host and runtime
151
+ * expects. Above that it stays a stream and must declare its length: the
152
+ * runtime fails a body that runs short or long of it, so the declared size is
153
+ * the stored size. On Workers the stream is re-wrapped at that length, so it
154
+ * keeps a known length across the hop to the channel's script (R2 needs one).
155
+ */
156
+ async function uploadBody(request, maxBytes) {
157
+ const header = request.headers.get("content-length");
158
+ const declared = header === null || header === "" ? null : Number(header);
159
+ if (declared !== null && (!Number.isSafeInteger(declared) || declared < 0)) return null;
160
+ if (declared !== null && declared > maxBytes) return null;
161
+ if (declared !== null && declared > 26214400 && request.body) {
162
+ const fixed = globalThis.FixedLengthStream;
163
+ return {
164
+ data: fixed ? request.body.pipeThrough(new fixed(declared)) : request.body,
165
+ size: declared
166
+ };
167
+ }
168
+ const cap = Math.min(maxBytes, BUFFERED_BLOB_BYTES);
169
+ const chunks = [];
170
+ let size = 0;
171
+ if (request.body) {
172
+ const reader = request.body.getReader();
173
+ for (;;) {
174
+ const { done, value } = await reader.read();
175
+ if (done) break;
176
+ size += value.byteLength;
177
+ if (size > cap) {
178
+ await reader.cancel().catch(() => {});
179
+ return null;
180
+ }
181
+ chunks.push(value);
182
+ }
183
+ }
184
+ const data = new Uint8Array(size);
185
+ let at = 0;
186
+ for (const chunk of chunks) {
187
+ data.set(chunk, at);
188
+ at += chunk.byteLength;
189
+ }
190
+ return {
191
+ data: data.buffer,
192
+ size
193
+ };
194
+ }
91
195
  function blobRouter(config) {
92
196
  const blob = new Hono();
197
+ const limitFor = (c) => config.maxBytes?.(c) ?? 26214400;
93
198
  const resolve = async (c) => config.store(c);
94
199
  blob.put("/blob/:key", async (c) => {
95
200
  const resolved = await resolve(c);
@@ -99,20 +204,31 @@ function blobRouter(config) {
99
204
  if (!key) return c.json({ error: "invalid_key" }, 400);
100
205
  const refused = await config.guard?.(c, "put");
101
206
  if (refused) return refused;
102
- if (Number(c.req.header("content-length") ?? 0) > MAX_BLOB_BYTES) return c.json({
103
- error: "blob_too_large",
104
- maxBytes: MAX_BLOB_BYTES
105
- }, 413);
106
- const body = await c.req.raw.arrayBuffer();
107
- if (body.byteLength > MAX_BLOB_BYTES) return c.json({
207
+ const link = config.uploadLink?.(c);
208
+ const limit = limitFor(c);
209
+ const maxBytes = link ? Math.min(link.maxBytes, limit) : limit;
210
+ if (link?.contentType && mediaType(c.req.header("content-type")) !== link.contentType) return c.json({
211
+ error: "content_type_mismatch",
212
+ detail: `this upload link only accepts ${link.contentType}`,
213
+ contentType: link.contentType
214
+ }, 415);
215
+ const body = await uploadBody(c.req.raw, maxBytes);
216
+ if (body === null) return c.json({
108
217
  error: "blob_too_large",
109
- maxBytes: MAX_BLOB_BYTES
218
+ maxBytes
110
219
  }, 413);
111
220
  const contentType = c.req.header("content-type") ?? "application/octet-stream";
112
- await store.bucket.put(store.prefix + key, body, { httpMetadata: { contentType } });
221
+ if (await store.bucket.put(store.prefix + key, body.data, {
222
+ httpMetadata: { contentType },
223
+ ...link && !link.overwrite && { onlyIf: createOnly() },
224
+ ...body.data instanceof ReadableStream && { contentLength: body.size }
225
+ }) === null) return c.json({
226
+ error: "blob_exists",
227
+ detail: "a file is already stored under this key, and this upload link only creates"
228
+ }, 409);
113
229
  return c.json({
114
230
  key,
115
- size: body.byteLength,
231
+ size: body.size,
116
232
  contentType,
117
233
  uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
118
234
  }, 201);
@@ -144,6 +260,41 @@ function blobRouter(config) {
144
260
  } while (cursor);
145
261
  return c.json(objects.slice(0, MAX_LIST_KEYS));
146
262
  });
263
+ blob.post("/blob/:key/upload-url", async (c) => {
264
+ const resolved = await resolve(c);
265
+ if (resolved instanceof Response) return resolved;
266
+ const { slug } = resolved;
267
+ const key = safeBlobKey(c.req.param("key"));
268
+ if (!key) return c.json({ error: "invalid_key" }, 400);
269
+ const refused = await config.guard?.(c, "put");
270
+ if (refused) return refused;
271
+ if (!config.signUpload) return c.json({
272
+ error: "not_supported",
273
+ detail: "upload links need the platform; upload directly here"
274
+ }, 501);
275
+ const options = uploadUrlOptions(await c.req.json().catch(() => ({})), limitFor(c));
276
+ if ("error" in options) return c.json(options, 400);
277
+ const exp = Math.floor(Date.now() / 1e3) + options.expiresIn;
278
+ const binding = {
279
+ maxBytes: options.maxBytes,
280
+ contentType: options.contentType,
281
+ overwrite: options.overwrite
282
+ };
283
+ const sig = await config.signUpload(c, slug, key, exp, binding);
284
+ const query = new URLSearchParams({
285
+ project: slug,
286
+ exp: String(exp),
287
+ max: String(binding.maxBytes),
288
+ ...binding.contentType && { type: binding.contentType },
289
+ mode: binding.overwrite ? "replace" : "create",
290
+ sig
291
+ });
292
+ return c.json({
293
+ url: `/_api/data/v1/blob/${encodeURIComponent(key)}?${query.toString()}`,
294
+ method: "PUT",
295
+ expiresAt: (/* @__PURE__ */ new Date(exp * 1e3)).toISOString()
296
+ });
297
+ });
147
298
  blob.get("/blob/:key/url", async (c) => {
148
299
  const resolved = await resolve(c);
149
300
  if (resolved instanceof Response) return resolved;
@@ -844,26 +995,184 @@ function realtimeRouter(config) {
844
995
  return realtime;
845
996
  }
846
997
  //#endregion
847
- //#region ../data-plane/src/worker-request.ts
848
- /** Gateway-stamped identity, for the worker's own `env.USER` / `env.CALLER` — never relayed. */
998
+ //#region ../data-plane/src/caller-headers.ts
999
+ /** env.USER: the signed-in Monk (directly, through an agent, or with a personal token). */
1000
+ const USER_SUB_HEADER = "x-canopy-user-sub";
1001
+ const USER_EMAIL_HEADER = "x-canopy-user-email";
1002
+ const USER_NAME_HEADER = "x-canopy-user-name";
1003
+ /**
1004
+ * env.CALLER: everyone the wall let through (worker-caller-identity). Never
1005
+ * folded into the user headers: a runtime reads those as "a Monk is
1006
+ * calling", and an older one would hand outsiders that standing.
1007
+ */
1008
+ const IDENTITY_KIND_HEADER = "x-canopy-identity-kind";
1009
+ const IDENTITY_ID_HEADER = "x-canopy-identity-id";
1010
+ const IDENTITY_EMAIL_HEADER = "x-canopy-identity-email";
1011
+ const IDENTITY_NAME_HEADER = "x-canopy-identity-name";
1012
+ /** Comma-joined app role slugs (project-roles); slugs hold no commas. Absent from an older gateway. */
1013
+ const IDENTITY_ROLES_HEADER = "x-canopy-identity-roles";
1014
+ /** `agent`: a tools call (docs/49) or an agent browse session. */
1015
+ const CALLER_HEADER = "x-canopy-caller";
1016
+ /**
1017
+ * A call from another project (project-calls): which project and channel,
1018
+ * and the visitor it acts for. Separate headers, so a runtime from before
1019
+ * project calls reads an unknown kind and leaves env.CALLER null.
1020
+ */
1021
+ const IDENTITY_PROJECT_HEADER = "x-canopy-identity-project";
1022
+ const IDENTITY_CHANNEL_HEADER = "x-canopy-identity-channel";
1023
+ const ACTING_KIND_HEADER = "x-canopy-acting-kind";
1024
+ const ACTING_ID_HEADER = "x-canopy-acting-id";
1025
+ const ACTING_EMAIL_HEADER = "x-canopy-acting-email";
1026
+ const ACTING_NAME_HEADER = "x-canopy-acting-name";
1027
+ const ACTING_AGENT_HEADER = "x-canopy-acting-agent";
1028
+ const ACTING_ROLES_HEADER = "x-canopy-acting-roles";
1029
+ /** An access-token call (project-access-tokens): the token's description, base64url JSON. */
1030
+ const TOKEN_HEADER = "x-canopy-token";
1031
+ /**
1032
+ * Gateway-stamped identity, for the backend's own env.USER / env.CALLER —
1033
+ * never relayed upstream by `CANOPY.fetch` (stampWorkerHeaders).
1034
+ */
849
1035
  const IDENTITY_STAMP_HEADERS = [
850
- "x-canopy-user-sub",
851
- "x-canopy-user-email",
852
- "x-canopy-user-name",
853
- "x-canopy-identity-kind",
854
- "x-canopy-identity-id",
855
- "x-canopy-identity-email",
856
- "x-canopy-identity-name",
857
- "x-canopy-identity-roles",
858
- "x-canopy-identity-project",
859
- "x-canopy-identity-channel",
860
- "x-canopy-acting-kind",
861
- "x-canopy-acting-id",
862
- "x-canopy-acting-email",
863
- "x-canopy-acting-name",
864
- "x-canopy-acting-agent",
865
- "x-canopy-acting-roles"
1036
+ USER_SUB_HEADER,
1037
+ USER_EMAIL_HEADER,
1038
+ USER_NAME_HEADER,
1039
+ IDENTITY_KIND_HEADER,
1040
+ IDENTITY_ID_HEADER,
1041
+ IDENTITY_EMAIL_HEADER,
1042
+ IDENTITY_NAME_HEADER,
1043
+ IDENTITY_ROLES_HEADER,
1044
+ IDENTITY_PROJECT_HEADER,
1045
+ IDENTITY_CHANNEL_HEADER,
1046
+ ACTING_KIND_HEADER,
1047
+ ACTING_ID_HEADER,
1048
+ ACTING_EMAIL_HEADER,
1049
+ ACTING_NAME_HEADER,
1050
+ ACTING_AGENT_HEADER,
1051
+ ACTING_ROLES_HEADER,
1052
+ TOKEN_HEADER
866
1053
  ];
1054
+ [...IDENTITY_STAMP_HEADERS];
1055
+ const header = (headers, name) => headers.get(name)?.trim() || "";
1056
+ const splitRoles = (raw) => raw.split(",").map((r) => r.trim()).filter(Boolean);
1057
+ /** `undefined` when the gateway sent no roles header (one older than project-roles). */
1058
+ function rolesFromHeaders(headers) {
1059
+ const raw = headers.get(IDENTITY_ROLES_HEADER);
1060
+ return raw === null ? void 0 : splitRoles(raw);
1061
+ }
1062
+ /** env.USER: the Monk the gateway stamped, or null. */
1063
+ function readUser(headers) {
1064
+ const sub = header(headers, USER_SUB_HEADER);
1065
+ if (!sub) return null;
1066
+ const roles = rolesFromHeaders(headers);
1067
+ return {
1068
+ sub,
1069
+ email: header(headers, USER_EMAIL_HEADER),
1070
+ name: header(headers, USER_NAME_HEADER),
1071
+ ...roles && { roles }
1072
+ };
1073
+ }
1074
+ function stringList(value) {
1075
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1076
+ }
1077
+ /** The gateway's token description, or null when absent or unreadable. */
1078
+ function readToken(headers) {
1079
+ const raw = header(headers, TOKEN_HEADER);
1080
+ if (!raw) return null;
1081
+ try {
1082
+ const binary = atob(raw.replaceAll("-", "+").replaceAll("_", "/"));
1083
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
1084
+ const value = JSON.parse(new TextDecoder().decode(bytes));
1085
+ if (!value || typeof value.id !== "string" || !value.id) return null;
1086
+ if (value.kind !== "personal" && value.kind !== "project") return null;
1087
+ return {
1088
+ id: value.id,
1089
+ name: typeof value.name === "string" ? value.name : "",
1090
+ kind: value.kind,
1091
+ scopes: stringList(value.scopes),
1092
+ paths: stringList(value.paths),
1093
+ methods: stringList(value.methods)
1094
+ };
1095
+ } catch {
1096
+ return null;
1097
+ }
1098
+ }
1099
+ /** A person caller (Monk or external) from the identity headers, or null for any other kind. */
1100
+ function readPersonCaller(headers) {
1101
+ const kind = header(headers, IDENTITY_KIND_HEADER);
1102
+ const id = header(headers, IDENTITY_ID_HEADER);
1103
+ if (kind !== "monk" && kind !== "external" || !id) return null;
1104
+ const roles = rolesFromHeaders(headers);
1105
+ const token = readToken(headers);
1106
+ return {
1107
+ kind,
1108
+ id,
1109
+ email: header(headers, IDENTITY_EMAIL_HEADER),
1110
+ name: header(headers, IDENTITY_NAME_HEADER),
1111
+ agent: headers.get(CALLER_HEADER) === "agent",
1112
+ ...roles && { roles },
1113
+ token: token?.kind === "personal" ? token : null
1114
+ };
1115
+ }
1116
+ //#endregion
1117
+ //#region ../data-plane/src/caller-headers.cases.ts
1118
+ const ada = {
1119
+ sub: "u-ada",
1120
+ email: "ada@monks.com",
1121
+ name: "Ada"
1122
+ };
1123
+ const personalToken = {
1124
+ id: "t1",
1125
+ name: "Figma plugin",
1126
+ kind: "personal",
1127
+ scopes: ["reports:read"],
1128
+ paths: ["/api/reports"],
1129
+ methods: ["GET"]
1130
+ };
1131
+ const projectToken = {
1132
+ id: "k1",
1133
+ name: "Jenkins",
1134
+ kind: "project",
1135
+ scopes: ["reports:write"],
1136
+ paths: [],
1137
+ methods: ["POST"]
1138
+ };
1139
+ /** base64url of the JSON, exactly as encodeTokenDescription writes it. */
1140
+ function b64(value) {
1141
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
1142
+ let binary = "";
1143
+ for (const b of bytes) binary += String.fromCharCode(b);
1144
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
1145
+ }
1146
+ const monkHeaders = {
1147
+ "x-canopy-user-sub": "u-ada",
1148
+ "x-canopy-user-email": "ada@monks.com",
1149
+ "x-canopy-user-name": "Ada",
1150
+ "x-canopy-identity-kind": "monk",
1151
+ "x-canopy-identity-id": "u-ada",
1152
+ "x-canopy-identity-email": "ada@monks.com",
1153
+ "x-canopy-identity-name": "Ada",
1154
+ "x-canopy-identity-roles": "user,editor"
1155
+ };
1156
+ ({ ...ada }), { ...monkHeaders }, { ...ada }, { ...monkHeaders }, b64(personalToken), { ...ada }, b64(projectToken), b64(personalToken), { ...monkHeaders }, b64(projectToken), { ...ada };
1157
+ //#endregion
1158
+ //#region ../data-plane/src/worker-request.ts
1159
+ /**
1160
+ * How a project's backend addresses the platform — the one definition.
1161
+ *
1162
+ * Three hosts run project workers and each builds this request itself: the
1163
+ * Workers-for-Platforms shim (packages/data-plane/src/worker-shim.ts), the Node
1164
+ * runtime (apps/project-runtime/src/canopy-fetch.ts), and `canopy dev`
1165
+ * (packages/cli/src/dev-worker.ts). They had three copies of the header
1166
+ * shaping, and the two that hold a worker token had two copies of the
1167
+ * credential rule — which is exactly how the Google project grant came to
1168
+ * work on one target and not the other.
1169
+ *
1170
+ * The shim cannot import this: it ships as a standalone module uploaded
1171
+ * beside the user bundle, so it may only import `./bundle.mjs`. It keeps a
1172
+ * transcription, and `wfp-shim.test.ts` runs it against the table in
1173
+ * `worker-request.cases.ts` alongside this implementation, so the two cannot
1174
+ * drift silently.
1175
+ */
867
1176
  /**
868
1177
  * Header carrying the project's worker token as runtime-origin proof (docs/35).
869
1178
  * The data plane verifies it to exempt the worker from browser DB access even
@@ -879,11 +1188,6 @@ const WORKER_ATTEST_HEADER = "x-canopy-worker-attest";
879
1188
  */
880
1189
  const AGENT_CREDENTIAL_HEADER = "x-canopy-agent-credential";
881
1190
  /**
882
- * Gateway-stamped marker on a tools call: `agent`. Never a credential, but
883
- * only the gateway may set it — it strips client copies on every dispatch.
884
- */
885
- const CALLER_HEADER = "x-canopy-caller";
886
- /**
887
1191
  * Cookies that authenticate to Canopy itself — the monk session, the
888
1192
  * client-page session, an agent's browse session and an outside account's
889
1193
  * session (outside-sign-in).
@@ -977,6 +1281,7 @@ const IDENTITY_STAMP_HEADERS = [
977
1281
  "x-canopy-acting-name",
978
1282
  "x-canopy-acting-agent",
979
1283
  "x-canopy-acting-roles",
1284
+ "x-canopy-token",
980
1285
  ];
981
1286
 
982
1287
  // App roles (project-roles) — transcribed from rolesFromHeaders in
@@ -1041,10 +1346,56 @@ function projectCallerFromHeaders(headers, id) {
1041
1346
  };
1042
1347
  }
1043
1348
 
1349
+ // env.CALLER.token (project-access-tokens) — transcribed from
1350
+ // tokenFromHeaders in project-runtime/src/user.ts: the gateway's base64url
1351
+ // JSON description of the access token a call came with, or null.
1352
+ function stringList(value) {
1353
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1354
+ }
1355
+
1356
+ function tokenFromHeaders(headers) {
1357
+ const raw = (headers.get("x-canopy-token") || "").trim();
1358
+ if (!raw) return null;
1359
+ try {
1360
+ const binary = atob(raw.replace(/-/g, "+").replace(/_/g, "/"));
1361
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
1362
+ const value = JSON.parse(new TextDecoder().decode(bytes));
1363
+ if (!value || typeof value.id !== "string" || !value.id) return null;
1364
+ if (value.kind !== "personal" && value.kind !== "project") return null;
1365
+ return {
1366
+ id: value.id,
1367
+ name: typeof value.name === "string" ? value.name : "",
1368
+ kind: value.kind,
1369
+ scopes: stringList(value.scopes),
1370
+ paths: stringList(value.paths),
1371
+ methods: stringList(value.methods),
1372
+ };
1373
+ } catch {
1374
+ return null;
1375
+ }
1376
+ }
1377
+
1044
1378
  function callerFromHeaders(headers) {
1045
1379
  const kind = (headers.get("x-canopy-identity-kind") || "").trim();
1046
1380
  const id = (headers.get("x-canopy-identity-id") || "").trim();
1047
- if (kind === "project" && id) return projectCallerFromHeaders(headers, id);
1381
+ if (kind === "project" && id) {
1382
+ const caller = projectCallerFromHeaders(headers, id);
1383
+ return caller && { ...caller, token: null };
1384
+ }
1385
+ const token = tokenFromHeaders(headers);
1386
+ // A project key (project-access-tokens): the project's own credential.
1387
+ if (kind === "key" && id) {
1388
+ if (!token || token.kind !== "project") return null;
1389
+ return {
1390
+ kind: "key",
1391
+ id,
1392
+ email: "",
1393
+ name: (headers.get("x-canopy-identity-name") || "").trim() || token.name,
1394
+ agent: false,
1395
+ roles: [],
1396
+ token,
1397
+ };
1398
+ }
1048
1399
  if ((kind !== "monk" && kind !== "external") || !id) return null;
1049
1400
  const roles = rolesFromHeaders(headers);
1050
1401
  return {
@@ -1054,6 +1405,7 @@ function callerFromHeaders(headers) {
1054
1405
  name: (headers.get("x-canopy-identity-name") || "").trim(),
1055
1406
  agent: headers.get("x-canopy-caller") === "agent",
1056
1407
  ...(roles && { roles }),
1408
+ token: token && token.kind === "personal" ? token : null,
1057
1409
  };
1058
1410
  }
1059
1411
 
@@ -1066,6 +1418,7 @@ function callerFromUser(user) {
1066
1418
  name: user.name,
1067
1419
  agent: false,
1068
1420
  ...(user.roles && { roles: user.roles }),
1421
+ token: null,
1069
1422
  }
1070
1423
  : null;
1071
1424
  }
@@ -1316,13 +1669,38 @@ async function handleBlobChannel(request, bucket) {
1316
1669
  headers: { "x-canopy-blob-meta": JSON.stringify(blobMeta(object)), ...BLOB_MARKER },
1317
1670
  });
1318
1671
  }
1319
- if (op === "put") {
1672
+ if (op === "put" || op === "put-if-absent") {
1320
1673
  const contentType = request.headers.get("x-canopy-blob-content-type");
1321
- await bucket.put(
1322
- key,
1323
- await request.arrayBuffer(),
1324
- contentType ? { httpMetadata: { contentType } } : undefined,
1325
- );
1674
+ // put-if-absent: R2's atomic create-only (If-None-Match: *) — the put
1675
+ // resolves to null instead of storing when the key already holds a file.
1676
+ const stored = await bucket.put(key, await request.arrayBuffer(), {
1677
+ ...(contentType && { httpMetadata: { contentType } }),
1678
+ ...(op === "put-if-absent" && { onlyIf: new Headers({ "if-none-match": "*" }) }),
1679
+ });
1680
+ if (stored === null) return blobJson({ error: "exists" }, 409);
1681
+ return blobJson({ ok: true });
1682
+ }
1683
+ if (op === "put-stream") {
1684
+ // A file over the buffered limit (blob-file-limits): the body goes to the
1685
+ // bucket as a stream, never into this isolate's memory. R2 needs a known
1686
+ // length, which the request's declared one gives; re-wrapping at it keeps
1687
+ // that true however the body arrived.
1688
+ const contentType = request.headers.get("x-canopy-blob-content-type");
1689
+ const length = Number(request.headers.get("content-length") || "");
1690
+ if (!request.body || !Number.isSafeInteger(length) || length < 0) {
1691
+ return blobJson({ error: "length_required" }, 411);
1692
+ }
1693
+ const body =
1694
+ typeof FixedLengthStream === "function"
1695
+ ? request.body.pipeThrough(new FixedLengthStream(length))
1696
+ : request.body;
1697
+ const stored = await bucket.put(key, body, {
1698
+ ...(contentType && { httpMetadata: { contentType } }),
1699
+ ...(request.headers.get("x-canopy-blob-create-only") === "1" && {
1700
+ onlyIf: new Headers({ "if-none-match": "*" }),
1701
+ }),
1702
+ });
1703
+ if (stored === null) return blobJson({ error: "exists" }, 409);
1326
1704
  return blobJson({ ok: true });
1327
1705
  }
1328
1706
  if (op === "delete") {
@@ -1753,4 +2131,4 @@ export default {
1753
2131
  };
1754
2132
  `;
1755
2133
  //#endregion
1756
- export { realtimeRouter as a, META_COLUMNS as c, stampWorkerHeaders as i, blobRouter as l, WORKER_ATTEST_HEADER as n, dbRouter as o, redactCanopyCredentials as r, hasPrivateNames as s, CALLER_HEADER as t };
2134
+ export { readPersonCaller as a, dbRouter as c, STREAMED_BLOB_BYTES as d, blobRouter as f, CALLER_HEADER as i, hasPrivateNames as l, redactCanopyCredentials as n, readUser as o, isCreateOnly as p, stampWorkerHeaders as r, realtimeRouter as s, WORKER_ATTEST_HEADER as t, META_COLUMNS as u };