@mediamonks/canopy-cli 0.7.50 → 0.7.52

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 (41) hide show
  1. package/dist/{dev-BQ77vmCk.mjs → dev-BnzJ8a1u.mjs} +5 -4
  2. package/dist/dev-DSI3e4qP.mjs +2 -0
  3. package/dist/{dev-worker-BP-HGHYb.mjs → dev-worker-DBBN0F6X.mjs} +15 -33
  4. package/dist/docs/access-tokens.md +145 -0
  5. package/dist/docs/calling-projects.md +9 -0
  6. package/dist/docs/ci.md +8 -0
  7. package/dist/docs/cli-dev.md +1 -1
  8. package/dist/docs/cli-files.md +57 -0
  9. package/dist/docs/cli.md +2 -0
  10. package/dist/docs/developers-architecture.md +20 -4
  11. package/dist/docs/index.json +20 -0
  12. package/dist/docs/outside-sign-in.md +79 -0
  13. package/dist/docs/overview-faq.md +4 -3
  14. package/dist/docs/platform-client-access.md +6 -0
  15. package/dist/docs/platform-credentials.md +76 -0
  16. package/dist/docs/platform-members-and-access.md +31 -6
  17. package/dist/docs/platform-project-data.md +11 -1
  18. package/dist/docs/sdk-auth.md +71 -21
  19. package/dist/docs/sdk-files.md +148 -3
  20. package/dist/docs/sdk-projects.md +2 -1
  21. package/dist/docs/sdk.md +17 -10
  22. package/dist/docs/staging.md +8 -0
  23. package/dist/docs/troubleshooting.md +20 -0
  24. package/dist/{docs-Cd6VzYts.mjs → docs-Od4duFhd.mjs} +1 -1
  25. package/dist/{feedback-BkrdL92o.mjs → feedback-XEIHbeor.mjs} +1 -1
  26. package/dist/files-B7toJRlj.mjs +69 -0
  27. package/dist/index.mjs +14 -12
  28. package/dist/{local-C6ggy2PQ.mjs → local-R-INkPbU.mjs} +17 -6
  29. package/dist/{mcp-Bt9Z9kdf.mjs → mcp-misDO7O8.mjs} +1 -1
  30. package/dist/{package-Sir3152_.mjs → package-DBdEKZ6u.mjs} +1 -1
  31. package/dist/{project-template-DHWdVc6E.mjs → project-template-Bas1UN2O.mjs} +1 -0
  32. package/dist/project-template-Dti_Mmnb.mjs +2 -0
  33. package/dist/{projects-Z8ufQIBc.mjs → projects-BEBYhy6k.mjs} +1 -1
  34. package/dist/skill/canopy/SKILL.md +9 -1
  35. package/dist/{skill-Bxc5E-wu.mjs → skill-3RZw4vSI.mjs} +1 -1
  36. package/dist/{src-DzU89gZN.mjs → src-UBUAqzqH.mjs} +442 -43
  37. package/dist/templates/worker/worker/index.ts +4 -0
  38. package/dist/{upgrade-DOpeMSWD.mjs → upgrade-Dy4XV7iP.mjs} +1 -1
  39. package/package.json +2 -2
  40. package/dist/dev-Z3bI5hgh.mjs +0 -2
  41. package/dist/project-template-ChFb7A_H.mjs +0 -2
@@ -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);
@@ -97,20 +202,33 @@ function blobRouter(config) {
97
202
  const { store } = resolved;
98
203
  const key = safeBlobKey(c.req.param("key"));
99
204
  if (!key) return c.json({ error: "invalid_key" }, 400);
100
- if (Number(c.req.header("content-length") ?? 0) > MAX_BLOB_BYTES) return c.json({
101
- error: "blob_too_large",
102
- maxBytes: MAX_BLOB_BYTES
103
- }, 413);
104
- const body = await c.req.raw.arrayBuffer();
105
- if (body.byteLength > MAX_BLOB_BYTES) return c.json({
205
+ const refused = await config.guard?.(c, "put");
206
+ if (refused) return refused;
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({
106
217
  error: "blob_too_large",
107
- maxBytes: MAX_BLOB_BYTES
218
+ maxBytes
108
219
  }, 413);
109
220
  const contentType = c.req.header("content-type") ?? "application/octet-stream";
110
- 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);
111
229
  return c.json({
112
230
  key,
113
- size: body.byteLength,
231
+ size: body.size,
114
232
  contentType,
115
233
  uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
116
234
  }, 201);
@@ -121,6 +239,8 @@ function blobRouter(config) {
121
239
  const { store } = resolved;
122
240
  const prefix = c.req.query("prefix") ?? "";
123
241
  if (prefix.length > 512 || prefix.includes("\0")) return c.json({ error: "invalid_prefix" }, 400);
242
+ const refused = await config.guard?.(c, "list");
243
+ if (refused) return refused;
124
244
  const base = store.prefix;
125
245
  const objects = [];
126
246
  let cursor;
@@ -140,12 +260,49 @@ function blobRouter(config) {
140
260
  } while (cursor);
141
261
  return c.json(objects.slice(0, MAX_LIST_KEYS));
142
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
+ });
143
298
  blob.get("/blob/:key/url", async (c) => {
144
299
  const resolved = await resolve(c);
145
300
  if (resolved instanceof Response) return resolved;
146
301
  const { slug, store } = resolved;
147
302
  const key = safeBlobKey(c.req.param("key"));
148
303
  if (!key) return c.json({ error: "invalid_key" }, 400);
304
+ const refused = await config.guard?.(c, "url");
305
+ if (refused) return refused;
149
306
  const ttl = requestedTtl(c.req.query("expiresIn"));
150
307
  if (ttl === null) return c.json({
151
308
  error: "invalid_expires_in",
@@ -165,6 +322,8 @@ function blobRouter(config) {
165
322
  const { store } = resolved;
166
323
  const key = safeBlobKey(c.req.param("key"));
167
324
  if (!key) return c.json({ error: "invalid_key" }, 400);
325
+ const refused = await config.guard?.(c, "get");
326
+ if (refused) return refused;
168
327
  const object = await store.bucket.get(store.prefix + key);
169
328
  if (!object) return c.json({ error: "not_found" }, 404);
170
329
  return new Response(object.body, { headers: {
@@ -178,6 +337,8 @@ function blobRouter(config) {
178
337
  const { store } = resolved;
179
338
  const key = safeBlobKey(c.req.param("key"));
180
339
  if (!key) return c.json({ error: "invalid_key" }, 400);
340
+ const refused = await config.guard?.(c, "delete");
341
+ if (refused) return refused;
181
342
  const fullKey = store.prefix + key;
182
343
  const existed = await store.bucket.head(fullKey) !== null;
183
344
  await store.bucket.delete(fullKey);
@@ -834,26 +995,184 @@ function realtimeRouter(config) {
834
995
  return realtime;
835
996
  }
836
997
  //#endregion
837
- //#region ../data-plane/src/worker-request.ts
838
- /** 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
+ */
839
1035
  const IDENTITY_STAMP_HEADERS = [
840
- "x-canopy-user-sub",
841
- "x-canopy-user-email",
842
- "x-canopy-user-name",
843
- "x-canopy-identity-kind",
844
- "x-canopy-identity-id",
845
- "x-canopy-identity-email",
846
- "x-canopy-identity-name",
847
- "x-canopy-identity-roles",
848
- "x-canopy-identity-project",
849
- "x-canopy-identity-channel",
850
- "x-canopy-acting-kind",
851
- "x-canopy-acting-id",
852
- "x-canopy-acting-email",
853
- "x-canopy-acting-name",
854
- "x-canopy-acting-agent",
855
- "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
856
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
+ */
857
1176
  /**
858
1177
  * Header carrying the project's worker token as runtime-origin proof (docs/35).
859
1178
  * The data plane verifies it to exempt the worker from browser DB access even
@@ -869,15 +1188,15 @@ const WORKER_ATTEST_HEADER = "x-canopy-worker-attest";
869
1188
  */
870
1189
  const AGENT_CREDENTIAL_HEADER = "x-canopy-agent-credential";
871
1190
  /**
872
- * Gateway-stamped marker on a tools call: `agent`. Never a credential, but
873
- * only the gateway may set it — it strips client copies on every dispatch.
1191
+ * Cookies that authenticate to Canopy itself — the monk session, the
1192
+ * client-page session, an agent's browse session and an outside account's
1193
+ * session (outside-sign-in).
874
1194
  */
875
- const CALLER_HEADER = "x-canopy-caller";
876
- /** Cookies that authenticate to Canopy itself — the monk session and the client-page session. */
877
1195
  const CANOPY_COOKIE_NAMES = /* @__PURE__ */ new Set([
878
1196
  "canopy_session",
879
1197
  "canopy_client",
880
- "canopy_agent"
1198
+ "canopy_agent",
1199
+ "canopy_outside_session"
881
1200
  ]);
882
1201
  /**
883
1202
  * Strip Canopy's own credentials from a request before untrusted project code
@@ -891,7 +1210,8 @@ const CANOPY_COOKIE_NAMES = /* @__PURE__ */ new Set([
891
1210
  *
892
1211
  * Redaction is surgical on purpose: an app's own cookies and its own
893
1212
  * Authorization scheme survive, because those belong to the app. Only
894
- * `canopy_session` / `canopy_client` / `canopy_agent` and a `cnpy_` bearer are removed.
1213
+ * `canopy_session` / `canopy_client` / `canopy_agent` / `canopy_outside_session` and a
1214
+ * `cnpy_` bearer are removed.
895
1215
  *
896
1216
  * `env.CANOPY.fetch` still authenticates as the visitor — the host passes it
897
1217
  * the unredacted headers — so nothing about the platform-facing behaviour
@@ -961,6 +1281,7 @@ const IDENTITY_STAMP_HEADERS = [
961
1281
  "x-canopy-acting-name",
962
1282
  "x-canopy-acting-agent",
963
1283
  "x-canopy-acting-roles",
1284
+ "x-canopy-token",
964
1285
  ];
965
1286
 
966
1287
  // App roles (project-roles) — transcribed from rolesFromHeaders in
@@ -1025,10 +1346,56 @@ function projectCallerFromHeaders(headers, id) {
1025
1346
  };
1026
1347
  }
1027
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
+
1028
1378
  function callerFromHeaders(headers) {
1029
1379
  const kind = (headers.get("x-canopy-identity-kind") || "").trim();
1030
1380
  const id = (headers.get("x-canopy-identity-id") || "").trim();
1031
- 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
+ }
1032
1399
  if ((kind !== "monk" && kind !== "external") || !id) return null;
1033
1400
  const roles = rolesFromHeaders(headers);
1034
1401
  return {
@@ -1038,6 +1405,7 @@ function callerFromHeaders(headers) {
1038
1405
  name: (headers.get("x-canopy-identity-name") || "").trim(),
1039
1406
  agent: headers.get("x-canopy-caller") === "agent",
1040
1407
  ...(roles && { roles }),
1408
+ token: token && token.kind === "personal" ? token : null,
1041
1409
  };
1042
1410
  }
1043
1411
 
@@ -1050,6 +1418,7 @@ function callerFromUser(user) {
1050
1418
  name: user.name,
1051
1419
  agent: false,
1052
1420
  ...(user.roles && { roles: user.roles }),
1421
+ token: null,
1053
1422
  }
1054
1423
  : null;
1055
1424
  }
@@ -1089,7 +1458,12 @@ function isControlPlanePath(raw) {
1089
1458
  }
1090
1459
 
1091
1460
  // Canopy's own cookies — platform credentials, never tenant-readable (R-01).
1092
- const CANOPY_COOKIE_NAMES = ["canopy_session", "canopy_client", "canopy_agent"];
1461
+ const CANOPY_COOKIE_NAMES = [
1462
+ "canopy_session",
1463
+ "canopy_client",
1464
+ "canopy_agent",
1465
+ "canopy_outside_session",
1466
+ ];
1093
1467
 
1094
1468
  // Strip Canopy's credentials from the request the bundle gets — a
1095
1469
  // transcription of redactCanopyCredentials in @mediamonks/canopy-data-plane,
@@ -1295,13 +1669,38 @@ async function handleBlobChannel(request, bucket) {
1295
1669
  headers: { "x-canopy-blob-meta": JSON.stringify(blobMeta(object)), ...BLOB_MARKER },
1296
1670
  });
1297
1671
  }
1298
- if (op === "put") {
1672
+ if (op === "put" || op === "put-if-absent") {
1299
1673
  const contentType = request.headers.get("x-canopy-blob-content-type");
1300
- await bucket.put(
1301
- key,
1302
- await request.arrayBuffer(),
1303
- contentType ? { httpMetadata: { contentType } } : undefined,
1304
- );
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);
1305
1704
  return blobJson({ ok: true });
1306
1705
  }
1307
1706
  if (op === "delete") {
@@ -1732,4 +2131,4 @@ export default {
1732
2131
  };
1733
2132
  `;
1734
2133
  //#endregion
1735
- 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 };
@@ -21,6 +21,10 @@ interface Env {
21
21
  USER: { sub: string; email: string; name: string } | null;
22
22
  // This project's slug.
23
23
  PROJECT_SLUG: string;
24
+ // Which channel this backend serves: "live", or "staging" for a
25
+ // `canopy deploy --staging` copy. Pass it as projects.fetch's `channel` to
26
+ // keep a staged backend off other projects' live data.
27
+ CANOPY_CHANNEL: "live" | "staging";
24
28
  // Raw handles, below the SDK, if you ever need them:
25
29
  // DB — this project's database: `dialect` plus
26
30
  // `query(text, params) => { rows, rowCount }`
@@ -112,7 +112,7 @@ const upgradeCommand = defineCommand({
112
112
  const spec = `${PACKAGE_NAME}@${args.version ?? "latest"}`;
113
113
  const command = pmCommand(pm);
114
114
  const cmd = installArgs(pm, spec);
115
- const { skillInstalled } = await import("./skill-Bxc5E-wu.mjs");
115
+ const { skillInstalled } = await import("./skill-3RZw4vSI.mjs");
116
116
  const { homedir } = await import("node:os");
117
117
  const refreshGlobal = skillInstalled(homedir());
118
118
  const refreshRepo = process.cwd() !== homedir() && skillInstalled(process.cwd());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mediamonks/canopy-cli",
3
- "version": "0.7.50",
3
+ "version": "0.7.52",
4
4
  "description": "Canopy CLI — create, develop and deploy Canopy projects.",
5
5
  "bin": {
6
6
  "canopy": "./dist/index.mjs"
@@ -22,7 +22,7 @@
22
22
  "esbuild": "^0.28.1",
23
23
  "hono": "^4.8.0",
24
24
  "vite-server": "npm:vite@^7",
25
- "@mediamonks/canopy": "0.0.15",
25
+ "@mediamonks/canopy": "0.0.19",
26
26
  "@mediamonks/canopy-data-plane": "0.0.4"
27
27
  },
28
28
  "devDependencies": {
@@ -1,2 +0,0 @@
1
- import { n as devCommand } from "./dev-BQ77vmCk.mjs";
2
- export { devCommand };
@@ -1,2 +0,0 @@
1
- import { a as templateCommand } from "./project-template-DHWdVc6E.mjs";
2
- export { templateCommand };