@samebase/alchemy-convex 0.46.0 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -174
- package/lib/index.d.ts +52 -3
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1691 -8
- package/lib/index.js.map +1 -1
- package/lib/sealedSecret.js +78 -1
- package/lib/sealedSecret.js.map +1 -0
- package/package.json +2 -9
- package/src/Providers.ts +2 -21
- package/lib/IdentityBroker-BqA_2V3_.js +0 -430
- package/lib/IdentityBroker-BqA_2V3_.js.map +0 -1
- package/lib/IdentityBroker.d.ts +0 -162
- package/lib/IdentityBroker.d.ts.map +0 -1
- package/lib/IdentityBroker.js +0 -1
- package/lib/Providers-zL1fUs0r.d.ts +0 -58
- package/lib/Providers-zL1fUs0r.d.ts.map +0 -1
- package/lib/State-Bp7iSx8T.js +0 -1699
- package/lib/State-Bp7iSx8T.js.map +0 -1
- package/lib/cli.d.ts +0 -1
- package/lib/cli.js +0 -218
- package/lib/cli.js.map +0 -1
- package/lib/sealedSecret-B7HlvIg2.js +0 -78
- package/lib/sealedSecret-B7HlvIg2.js.map +0 -1
- package/src/IdentityBroker.ts +0 -849
- package/src/StackComment.ts +0 -329
- package/src/cli.ts +0 -33
package/lib/cli.js
DELETED
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { n as state } from "./State-Bp7iSx8T.js";
|
|
3
|
-
import * as Effect from "effect/Effect";
|
|
4
|
-
import * as Schema from "effect/Schema";
|
|
5
|
-
import * as Layer from "effect/Layer";
|
|
6
|
-
import * as Option from "effect/Option";
|
|
7
|
-
import { parseArgs } from "node:util";
|
|
8
|
-
import { State } from "alchemy/State";
|
|
9
|
-
import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
|
|
10
|
-
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
11
|
-
import { boxSubtitle, stageDiagram, stageTree } from "@samebase/alchemy-kit/stack";
|
|
12
|
-
import { resourceTypeUI } from "@samebase/alchemy-kit/ui";
|
|
13
|
-
//#region src/StackComment.ts
|
|
14
|
-
/** The first text of the comment, which finds it again. */
|
|
15
|
-
const MARKER = "<!-- samebase-stacks -->";
|
|
16
|
-
/** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */
|
|
17
|
-
const ICONS = "https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment";
|
|
18
|
-
const GITHUB_API = "https://api.github.com";
|
|
19
|
-
/** The fields of the run record that a card shows. */
|
|
20
|
-
const StageOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
|
|
21
|
-
headCommit: Schema.String,
|
|
22
|
-
runUrl: Schema.NullOr(Schema.String),
|
|
23
|
-
recordedAt: Schema.String
|
|
24
|
-
}) });
|
|
25
|
-
/** The part of a stage output that says which repository deployed it. */
|
|
26
|
-
const RepositoryOfOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
|
|
27
|
-
version: Schema.Literal(2),
|
|
28
|
-
repositoryId: Schema.String,
|
|
29
|
-
stackFile: Schema.String
|
|
30
|
-
}) });
|
|
31
|
-
var StackCommentError = class extends Schema.TaggedError()("StackCommentError", { reason: Schema.String }) {
|
|
32
|
-
get message() {
|
|
33
|
-
return `The stack comment cannot be updated: ${this.reason}`;
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* The cards of the stacks of the repository that have `stage`, in name order. A stage with a version
|
|
38
|
-
* 2 record belongs to the repository of its `repositoryId`, under any stack name; any other stage
|
|
39
|
-
* belongs to the stacks named `repository` or `repository/<folder>`.
|
|
40
|
-
*/
|
|
41
|
-
const readStackCards = ({ repository, repositoryId, stage }) => Effect.gen(function* () {
|
|
42
|
-
const state = yield* yield* State;
|
|
43
|
-
const cards = [];
|
|
44
|
-
for (const name of yield* state.listStacks()) {
|
|
45
|
-
if (!(yield* state.listStages(name)).includes(stage)) continue;
|
|
46
|
-
const request = {
|
|
47
|
-
stack: name,
|
|
48
|
-
stage
|
|
49
|
-
};
|
|
50
|
-
const output = yield* state.getOutput(request);
|
|
51
|
-
const underName = name === repository || name.startsWith(`${repository}/`);
|
|
52
|
-
const record = Option.map(Schema.decodeUnknownOption(RepositoryOfOutput)(output), (decoded) => decoded[RUN_RECORD_KEY]);
|
|
53
|
-
if (Option.isSome(record) ? record.value.repositoryId !== repositoryId : !underName) continue;
|
|
54
|
-
const rows = yield* Effect.forEach(yield* state.list(request), (fqn) => state.get({
|
|
55
|
-
...request,
|
|
56
|
-
fqn
|
|
57
|
-
}).pipe(Effect.map((row) => ({
|
|
58
|
-
fqn,
|
|
59
|
-
state: row
|
|
60
|
-
}))));
|
|
61
|
-
cards.push({
|
|
62
|
-
name,
|
|
63
|
-
folder: underName || Option.isNone(record) ? name.slice(repository.length + 1) : record.value.stackFile.split("/").slice(0, -1).join("/"),
|
|
64
|
-
stage,
|
|
65
|
-
diagram: stageDiagram(rows),
|
|
66
|
-
run: Schema.is(StageOutput)(output) ? output : null
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
return cards;
|
|
70
|
-
});
|
|
71
|
-
const escapeHtml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
72
|
-
const link = (href, text) => `<a href="${escapeHtml(href)}">${text}</a>`;
|
|
73
|
-
const hostOf = (url) => escapeHtml(new URL(url).host);
|
|
74
|
-
/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */
|
|
75
|
-
const ICON_FILES = /* @__PURE__ */ new Map([
|
|
76
|
-
["Convex.Deployment", "convex"],
|
|
77
|
-
["Cloudflare.Worker", "worker"],
|
|
78
|
-
["Cloudflare.R2.Bucket", "r2"]
|
|
79
|
-
]);
|
|
80
|
-
/** The name of a box, as a link to its dashboard page when it has one. */
|
|
81
|
-
const boxName = ({ name, resourceType, rows: [first] }) => {
|
|
82
|
-
const icon = ICON_FILES.get(resourceType);
|
|
83
|
-
const image = icon === void 0 ? null : `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="">`;
|
|
84
|
-
const text = escapeHtml(name);
|
|
85
|
-
const href = first.dashboard?.href;
|
|
86
|
-
if (href === void 0) return image === null ? text : `${image} ${text}`;
|
|
87
|
-
return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;
|
|
88
|
-
};
|
|
89
|
-
/**
|
|
90
|
-
A box of the tree: its name with the labels of its line as code, its type and schedule, and its link
|
|
91
|
-
on the next line unless the link is the stage address. Below it, in a list: the boxes that it uses,
|
|
92
|
-
its bindings that name no box, the rows folded into it, and the boxes that share a resource with it.
|
|
93
|
-
A repeated box has only its name.
|
|
94
|
-
*/
|
|
95
|
-
const treeNode = (node, address) => {
|
|
96
|
-
const { box, labels, repeated } = node;
|
|
97
|
-
const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join("")}`;
|
|
98
|
-
if (repeated) return title;
|
|
99
|
-
const linkLine = box.link === null || box.link === address ? "" : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;
|
|
100
|
-
const below = [
|
|
101
|
-
...node.children.map((child) => treeNode(child, address)),
|
|
102
|
-
...box.bindings.filter((binding) => binding.box === null).map((binding) => `<code>${escapeHtml(binding.name)}</code> <sub>${escapeHtml([binding.kind, binding.target].filter((part) => part !== null).join(", "))}</sub>`),
|
|
103
|
-
...box.folded.map((row) => `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`),
|
|
104
|
-
...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`)
|
|
105
|
-
];
|
|
106
|
-
const list = below.length === 0 ? "" : `<ul>${below.map((item) => `<li>${item}</li>`).join("")}</ul>`;
|
|
107
|
-
return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;
|
|
108
|
-
};
|
|
109
|
-
/** Where a stage serves: its Convex app, else the first box with a link. */
|
|
110
|
-
const addressOf = ({ boxes }) => (boxes.find((box) => box.resourceType === "Convex.Deployment") ?? boxes.find((box) => box.link))?.link ?? null;
|
|
111
|
-
const runLine = ({ run }) => {
|
|
112
|
-
if (run === null) return "";
|
|
113
|
-
const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];
|
|
114
|
-
const commit = escapeHtml(headCommit.slice(0, 7));
|
|
115
|
-
const time = `${recordedAt.slice(0, 16).replace("T", " ")} UTC`;
|
|
116
|
-
return `<br><sub>${runUrl === null ? commit : link(runUrl, commit)} ${escapeHtml(time)}</sub>`;
|
|
117
|
-
};
|
|
118
|
-
const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
|
|
119
|
-
/** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
|
|
120
|
-
const renderCard = (card, alone) => {
|
|
121
|
-
const { folder } = card;
|
|
122
|
-
const heading = [folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `, `<sub>${escapeHtml(card.stage)}</sub>`].join("");
|
|
123
|
-
const address = addressOf(card.diagram);
|
|
124
|
-
const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
|
|
125
|
-
const rows = stageTree(card.diagram).map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`).join("\n");
|
|
126
|
-
return `<table>
|
|
127
|
-
<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
|
|
128
|
-
${rows}
|
|
129
|
-
</table>`;
|
|
130
|
-
};
|
|
131
|
-
const renderStackComment = (cards) => `${MARKER}
|
|
132
|
-
${cards.map((card) => renderCard(card, cards.length === 1)).join("\n\n")}
|
|
133
|
-
`;
|
|
134
|
-
const Comments = Schema.Array(Schema.Struct({
|
|
135
|
-
id: Schema.Number,
|
|
136
|
-
body: Schema.String
|
|
137
|
-
}));
|
|
138
|
-
const SavedComment = Schema.Struct({ html_url: Schema.String });
|
|
139
|
-
const github = (token, path, init) => Effect.tryPromise({
|
|
140
|
-
try: async () => {
|
|
141
|
-
const response = await fetch(`${GITHUB_API}${path}`, {
|
|
142
|
-
...init,
|
|
143
|
-
headers: {
|
|
144
|
-
Accept: "application/vnd.github+json",
|
|
145
|
-
Authorization: `Bearer ${token}`,
|
|
146
|
-
"Content-Type": "application/json",
|
|
147
|
-
"X-GitHub-Api-Version": "2022-11-28"
|
|
148
|
-
}
|
|
149
|
-
});
|
|
150
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
151
|
-
return await response.json();
|
|
152
|
-
},
|
|
153
|
-
catch: (error) => new StackCommentError({ reason: `GitHub ${init.method} ${path} failed (${error instanceof Error ? error.message : String(error)})` })
|
|
154
|
-
});
|
|
155
|
-
const decode = (schema, what) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => new StackCommentError({ reason: `GitHub gave a bad ${what}` })));
|
|
156
|
-
const findComment = (token, path) => Effect.gen(function* () {
|
|
157
|
-
for (let page = 1;; page += 1) {
|
|
158
|
-
const comments = yield* github(token, `${path}?per_page=100&page=${page}`, { method: "GET" }).pipe(Effect.flatMap(decode(Comments, "comment list")));
|
|
159
|
-
const comment = comments.find(({ body }) => body.startsWith(MARKER));
|
|
160
|
-
if (comment !== void 0 || comments.length < 100) return comment;
|
|
161
|
-
}
|
|
162
|
-
});
|
|
163
|
-
/** Replaces the body of the comment of this command, or posts it on the first run, and gives its URL. */
|
|
164
|
-
const saveStackComment = (args) => Effect.gen(function* () {
|
|
165
|
-
const { body, pullRequest, repository, token } = args;
|
|
166
|
-
const comments = `/repos/${repository}/issues/${pullRequest}/comments`;
|
|
167
|
-
const comment = yield* findComment(token, comments);
|
|
168
|
-
const reply = yield* comment === void 0 ? github(token, comments, {
|
|
169
|
-
method: "POST",
|
|
170
|
-
body: JSON.stringify({ body })
|
|
171
|
-
}) : github(token, `/repos/${repository}/issues/comments/${comment.id}`, {
|
|
172
|
-
method: "PATCH",
|
|
173
|
-
body: JSON.stringify({ body })
|
|
174
|
-
});
|
|
175
|
-
return (yield* decode(SavedComment, "comment")(reply)).html_url;
|
|
176
|
-
});
|
|
177
|
-
/** The step of a workflow: the run record names the repository and the pull request of the run. */
|
|
178
|
-
const updateStackComment = Effect.gen(function* () {
|
|
179
|
-
const { pullRequest, repositoryId, repositoryName: repository } = yield* runRecord({
|
|
180
|
-
cwd: process.cwd(),
|
|
181
|
-
env: process.env
|
|
182
|
-
});
|
|
183
|
-
if (pullRequest === null) return yield* new StackCommentError({ reason: "this run has no pull request" });
|
|
184
|
-
const token = process.env["GITHUB_TOKEN"];
|
|
185
|
-
if (token === void 0 || token === "") return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
|
|
186
|
-
const cards = yield* readStackCards({
|
|
187
|
-
repository,
|
|
188
|
-
repositoryId,
|
|
189
|
-
stage: `pr-${pullRequest}`
|
|
190
|
-
});
|
|
191
|
-
return yield* saveStackComment({
|
|
192
|
-
token,
|
|
193
|
-
repository,
|
|
194
|
-
pullRequest,
|
|
195
|
-
body: renderStackComment(cards)
|
|
196
|
-
});
|
|
197
|
-
});
|
|
198
|
-
//#endregion
|
|
199
|
-
//#region src/cli.ts
|
|
200
|
-
const { positionals } = parseArgs({
|
|
201
|
-
allowPositionals: true,
|
|
202
|
-
options: {}
|
|
203
|
-
});
|
|
204
|
-
const USAGE = `Usage:
|
|
205
|
-
alchemy-convex stack-comment`;
|
|
206
|
-
const stackComment = updateStackComment.pipe(Effect.tap((url) => Effect.sync(() => console.log(url))), Effect.provide(state().pipe(Layer.provide(NodeServices.layer))));
|
|
207
|
-
if (positionals.join(" ") !== "stack-comment") {
|
|
208
|
-
console.error(USAGE);
|
|
209
|
-
process.exit(1);
|
|
210
|
-
}
|
|
211
|
-
await Effect.runPromise(stackComment).catch((error) => {
|
|
212
|
-
console.error(error instanceof Error ? error.message : String(error));
|
|
213
|
-
process.exit(1);
|
|
214
|
-
});
|
|
215
|
-
//#endregion
|
|
216
|
-
export {};
|
|
217
|
-
|
|
218
|
-
//# sourceMappingURL=cli.js.map
|
package/lib/cli.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/StackComment.ts","../src/cli.ts"],"sourcesContent":["// The command `alchemy-convex stack-comment`: one comment on a pull request with the stacks of the\n// repository, read from the state store after the deploys.\n//\n// A stack sees only itself, so a comment that a stack declares cannot show the other stacks of the\n// repository. This command runs as a step after them and reads each stack of the repository that\n// has the stage `pr-<number>`: by the repository id of the stage's run record, or, for a stage\n// without a version 2 record, by the name `owner/name` or `owner/name/<folder>`. A stack without\n// that stage has no card. A run replaces the whole body, so the last run shows the newest state.\n//\n// The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model\n// of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no\n// secret of a row.\n//\n// GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of\n// the markup is a fact about the sanitizer or the CSS of github.com:\n// - A table has `display: block` and `width: max-content`, so a `width` on it does nothing. The\n// spacer, a floated image one pixel high in a block of its own, gives every card one width, and\n// it shrinks on a narrow page.\n// - The CSS colors the even rows of a group, so each row has its own `tbody`.\n// - An HTML block ends at a blank line, so a table has none and is not indented.\n// - A bare image links to its raw file, and one link around an image and text underlines the space\n// between them, so the icon and the name are two links to one place.\n// - An image with `height` gets a gray background, so each icon is square and has only `width`.\n// - `align=\"middle\"` is `-webkit-baseline-middle` in Chrome, which is below the text.\n// `align=\"absmiddle\"` is the CSS value `middle`.\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { RUN_RECORD_KEY, runRecord } from \"@samebase/alchemy-kit/run-record\";\nimport {\n boxSubtitle,\n stageDiagram,\n stageTree,\n type DiagramBox,\n type StageDiagram,\n type StageTreeNode,\n} from \"@samebase/alchemy-kit/stack\";\nimport { resourceTypeUI } from \"@samebase/alchemy-kit/ui\";\n\n/** The first text of the comment, which finds it again. */\nconst MARKER = \"<!-- samebase-stacks -->\";\n\n/** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */\nconst ICONS =\n \"https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment\";\n\nconst GITHUB_API = \"https://api.github.com\";\n\n/** The fields of the run record that a card shows. */\nconst StageOutput = Schema.Struct({\n [RUN_RECORD_KEY]: Schema.Struct({\n headCommit: Schema.String,\n runUrl: Schema.NullOr(Schema.String),\n recordedAt: Schema.String,\n }),\n});\n\n/** The part of a stage output that says which repository deployed it. */\nconst RepositoryOfOutput = Schema.Struct({\n [RUN_RECORD_KEY]: Schema.Struct({\n version: Schema.Literal(2),\n repositoryId: Schema.String,\n stackFile: Schema.String,\n }),\n});\n\nexport interface StackCard {\n readonly name: string;\n /** The folder of the stack file in the repository, \"\" at the root. */\n readonly folder: string;\n readonly stage: string;\n readonly diagram: StageDiagram;\n readonly run: typeof StageOutput.Type | null;\n}\n\nexport class StackCommentError extends Schema.TaggedError<StackCommentError>()(\n \"StackCommentError\",\n { reason: Schema.String },\n) {\n override get message() {\n return `The stack comment cannot be updated: ${this.reason}`;\n }\n}\n\n/**\n * The cards of the stacks of the repository that have `stage`, in name order. A stage with a version\n * 2 record belongs to the repository of its `repositoryId`, under any stack name; any other stage\n * belongs to the stacks named `repository` or `repository/<folder>`.\n */\nexport const readStackCards = ({\n repository,\n repositoryId,\n stage,\n}: {\n repository: string;\n repositoryId: string;\n stage: string;\n}) =>\n Effect.gen(function* () {\n const state = yield* yield* State;\n const cards: StackCard[] = [];\n for (const name of yield* state.listStacks()) {\n if (!(yield* state.listStages(name)).includes(stage)) {\n continue;\n }\n const request = { stack: name, stage };\n const output = yield* state.getOutput(request);\n const underName = name === repository || name.startsWith(`${repository}/`);\n const record = Option.map(\n Schema.decodeUnknownOption(RepositoryOfOutput)(output),\n (decoded) => decoded[RUN_RECORD_KEY],\n );\n if (Option.isSome(record) ? record.value.repositoryId !== repositoryId : !underName) {\n continue;\n }\n const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>\n state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),\n );\n cards.push({\n name,\n folder:\n underName || Option.isNone(record)\n ? name.slice(repository.length + 1)\n : record.value.stackFile.split(\"/\").slice(0, -1).join(\"/\"),\n stage,\n diagram: stageDiagram(rows),\n run: Schema.is(StageOutput)(output) ? output : null,\n });\n }\n return cards;\n });\n\nconst escapeHtml = (text: string) =>\n text\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\");\n\nconst link = (href: string, text: string) => `<a href=\"${escapeHtml(href)}\">${text}</a>`;\n\nconst hostOf = (url: string) => escapeHtml(new URL(url).host);\n\n/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */\nconst ICON_FILES = new Map([\n [\"Convex.Deployment\", \"convex\"],\n [\"Cloudflare.Worker\", \"worker\"],\n [\"Cloudflare.R2.Bucket\", \"r2\"],\n]);\n\n/** The name of a box, as a link to its dashboard page when it has one. */\nconst boxName = ({ name, resourceType, rows: [first] }: DiagramBox) => {\n const icon = ICON_FILES.get(resourceType);\n const image =\n icon === undefined\n ? null\n : `<img src=\"${ICONS}/${icon}.svg\" width=\"16\" align=\"absmiddle\" alt=\"\">`;\n const text = escapeHtml(name);\n const href = first.dashboard?.href;\n if (href === undefined) {\n return image === null ? text : `${image} ${text}`;\n }\n return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;\n};\n\n/**\nA box of the tree: its name with the labels of its line as code, its type and schedule, and its link\non the next line unless the link is the stage address. Below it, in a list: the boxes that it uses,\nits bindings that name no box, the rows folded into it, and the boxes that share a resource with it.\nA repeated box has only its name.\n*/\nconst treeNode = (node: StageTreeNode, address: string | null): string => {\n const { box, labels, repeated } = node;\n const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join(\"\")}`;\n if (repeated) {\n return title;\n }\n const linkLine =\n box.link === null || box.link === address\n ? \"\"\n : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;\n const below = [\n ...node.children.map((child) => treeNode(child, address)),\n ...box.bindings\n .filter((binding) => binding.box === null)\n .map(\n (binding) =>\n `<code>${escapeHtml(binding.name)}</code> <sub>${escapeHtml([binding.kind, binding.target].filter((part) => part !== null).join(\", \"))}</sub>`,\n ),\n ...box.folded.map(\n (row) =>\n `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`,\n ),\n ...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`),\n ];\n const list =\n below.length === 0 ? \"\" : `<ul>${below.map((item) => `<li>${item}</li>`).join(\"\")}</ul>`;\n return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;\n};\n\n/** Where a stage serves: its Convex app, else the first box with a link. */\nconst addressOf = ({ boxes }: StageDiagram) =>\n (boxes.find((box) => box.resourceType === \"Convex.Deployment\") ?? boxes.find((box) => box.link))\n ?.link ?? null;\n\nconst runLine = ({ run }: StackCard) => {\n if (run === null) {\n return \"\";\n }\n const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];\n const commit = escapeHtml(headCommit.slice(0, 7));\n const time = `${recordedAt.slice(0, 16).replace(\"T\", \" \")} UTC`;\n return `<br><sub>${runUrl === null ? commit : link(runUrl, commit)} ${escapeHtml(time)}</sub>`;\n};\n\nconst SPACER = `<div><img src=\"${ICONS}/spacer.svg\" width=\"460\" align=\"left\" alt=\"\"></div>`;\n\n/** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */\nconst renderCard = (card: StackCard, alone: boolean) => {\n const { folder } = card;\n const heading = [\n folder === \"\" && alone ? \"\" : `<b>${escapeHtml(folder || \"/\")}</b> `,\n `<sub>${escapeHtml(card.stage)}</sub>`,\n ].join(\"\");\n const address = addressOf(card.diagram);\n const addressLine = address === null ? \"\" : `<br>${link(address, hostOf(address))}`;\n const rows = stageTree(card.diagram)\n .map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`)\n .join(\"\\n\");\n return `<table>\n<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>\n${rows}\n</table>`;\n};\n\nexport const renderStackComment = (cards: readonly StackCard[]) => `${MARKER}\n${cards.map((card) => renderCard(card, cards.length === 1)).join(\"\\n\\n\")}\n`;\n\nconst Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));\nconst SavedComment = Schema.Struct({ html_url: Schema.String });\n\nconst github = (token: string, path: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async (): Promise<unknown> => {\n const response = await fetch(`${GITHUB_API}${path}`, {\n ...init,\n headers: {\n Accept: \"application/vnd.github+json\",\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return await response.json();\n },\n catch: (error) =>\n new StackCommentError({\n reason: `GitHub ${init.method} ${path} failed (${error instanceof Error ? error.message : String(error)})`,\n }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, what: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new StackCommentError({ reason: `GitHub gave a bad ${what}` })),\n );\n\nconst findComment = (token: string, path: string) =>\n Effect.gen(function* () {\n for (let page = 1; ; page += 1) {\n const comments = yield* github(token, `${path}?per_page=100&page=${page}`, {\n method: \"GET\",\n }).pipe(Effect.flatMap(decode(Comments, \"comment list\")));\n const comment = comments.find(({ body }) => body.startsWith(MARKER));\n if (comment !== undefined || comments.length < 100) {\n return comment;\n }\n }\n });\n\n/** Replaces the body of the comment of this command, or posts it on the first run, and gives its URL. */\nexport const saveStackComment = (args: {\n readonly token: string;\n readonly repository: string;\n readonly pullRequest: number;\n readonly body: string;\n}) =>\n Effect.gen(function* () {\n const { body, pullRequest, repository, token } = args;\n const comments = `/repos/${repository}/issues/${pullRequest}/comments`;\n const comment = yield* findComment(token, comments);\n const reply = yield* comment === undefined\n ? github(token, comments, { method: \"POST\", body: JSON.stringify({ body }) })\n : github(token, `/repos/${repository}/issues/comments/${comment.id}`, {\n method: \"PATCH\",\n body: JSON.stringify({ body }),\n });\n const saved = yield* decode(SavedComment, \"comment\")(reply);\n return saved.html_url;\n });\n\n/** The step of a workflow: the run record names the repository and the pull request of the run. */\nexport const updateStackComment = Effect.gen(function* () {\n const {\n pullRequest,\n repositoryId,\n repositoryName: repository,\n } = yield* runRecord({ cwd: process.cwd(), env: process.env });\n if (pullRequest === null) {\n return yield* new StackCommentError({ reason: \"this run has no pull request\" });\n }\n const token = process.env[\"GITHUB_TOKEN\"];\n if (token === undefined || token === \"\") {\n return yield* new StackCommentError({ reason: \"GITHUB_TOKEN is not set\" });\n }\n const cards = yield* readStackCards({ repository, repositoryId, stage: `pr-${pullRequest}` });\n return yield* saveStackComment({\n token,\n repository,\n pullRequest,\n body: renderStackComment(cards),\n });\n});\n","#!/usr/bin/env node\n// The command of the package:\n//\n// alchemy-convex stack-comment\n//\n// stack-comment runs as a step of a pull request workflow after the deploys, and keeps one comment\n// with the stacks of the repository: see src/StackComment.ts. It needs GITHUB_TOKEN, and reads the\n// store of the team of CONVEX_ACCESS_TOKEN or of the Convex CLI login.\nimport { parseArgs } from \"node:util\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { updateStackComment } from \"./StackComment.ts\";\nimport { state } from \"./State.ts\";\n\nconst { positionals } = parseArgs({ allowPositionals: true, options: {} });\nconst USAGE = `Usage:\n alchemy-convex stack-comment`;\n\nconst stackComment = updateStackComment.pipe(\n Effect.tap((url) => Effect.sync(() => console.log(url))),\n Effect.provide(state().pipe(Layer.provide(NodeServices.layer))),\n);\n\nif (positionals.join(\" \") !== \"stack-comment\") {\n console.error(USAGE);\n process.exit(1);\n}\n\nawait Effect.runPromise(stackComment).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;AAyCA,MAAM,SAAS;;AAGf,MAAM,QACJ;AAEF,MAAM,aAAa;;AAGnB,MAAM,cAAc,OAAO,OAAO,GAC/B,iBAAiB,OAAO,OAAO;CAC9B,YAAY,OAAO;CACnB,QAAQ,OAAO,OAAO,OAAO,MAAM;CACnC,YAAY,OAAO;AACrB,CAAC,EACH,CAAC;;AAGD,MAAM,qBAAqB,OAAO,OAAO,GACtC,iBAAiB,OAAO,OAAO;CAC9B,SAAS,OAAO,QAAQ,CAAC;CACzB,cAAc,OAAO;CACrB,WAAW,OAAO;AACpB,CAAC,EACH,CAAC;AAWD,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EAAE,QAAQ,OAAO,OAAO,CAC1B,CAAC,CAAC;CACA,IAAa,UAAU;EACrB,OAAO,wCAAwC,KAAK;CACtD;AACF;;;;;;AAOA,MAAa,kBAAkB,EAC7B,YACA,cACA,YAMA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,QAAqB,CAAC;CAC5B,KAAK,MAAM,QAAQ,OAAO,MAAM,WAAW,GAAG;EAC5C,IAAI,EAAE,OAAO,MAAM,WAAW,IAAI,EAAA,CAAG,SAAS,KAAK,GACjD;EAEF,MAAM,UAAU;GAAE,OAAO;GAAM;EAAM;EACrC,MAAM,SAAS,OAAO,MAAM,UAAU,OAAO;EAC7C,MAAM,YAAY,SAAS,cAAc,KAAK,WAAW,GAAG,WAAW,EAAE;EACzE,MAAM,SAAS,OAAO,IACpB,OAAO,oBAAoB,kBAAkB,CAAC,CAAC,MAAM,IACpD,YAAY,QAAQ,eACvB;EACA,IAAI,OAAO,OAAO,MAAM,IAAI,OAAO,MAAM,iBAAiB,eAAe,CAAC,WACxE;EAEF,MAAM,O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iB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
//#region src/store/sealedSecret.ts
|
|
2
|
-
const toBase64 = (bytes) => btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
|
|
3
|
-
const toBase64Url = (bytes) => toBase64(bytes).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
4
|
-
/** The bytes of base64 or base64url text. */
|
|
5
|
-
const fromBase64 = (text) => {
|
|
6
|
-
const standard = text.replaceAll("-", "+").replaceAll("_", "/");
|
|
7
|
-
const padded = standard.padEnd(standard.length + (4 - standard.length % 4) % 4, "=");
|
|
8
|
-
return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
|
|
9
|
-
};
|
|
10
|
-
/** A key of 32 bytes in base64 is 43 characters and one `=`. */
|
|
11
|
-
const KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;
|
|
12
|
-
/**
|
|
13
|
-
* The key ring in the text of the variable `name`. It fails closed when the text is missing or
|
|
14
|
-
* malformed, or when the current key id has no key. An error never quotes the text, which holds
|
|
15
|
-
* the keys.
|
|
16
|
-
*/
|
|
17
|
-
const parseKeyRing = (name, text) => {
|
|
18
|
-
let value;
|
|
19
|
-
try {
|
|
20
|
-
value = JSON.parse(text ?? "");
|
|
21
|
-
} catch {
|
|
22
|
-
throw new Error(`${name} is missing or is not JSON.`);
|
|
23
|
-
}
|
|
24
|
-
const malformed = /* @__PURE__ */ new Error(`${name} must be {"current":"<keyId>","keys":{"<keyId>":"<base64 of 32 bytes>"}}.`);
|
|
25
|
-
if (typeof value !== "object" || value === null) throw malformed;
|
|
26
|
-
if (!("current" in value) || !("keys" in value)) throw malformed;
|
|
27
|
-
const { current, keys: keyTexts } = value;
|
|
28
|
-
if (typeof current !== "string" || typeof keyTexts !== "object" || keyTexts === null) throw malformed;
|
|
29
|
-
const keys = /* @__PURE__ */ new Map();
|
|
30
|
-
for (const [keyId, key] of Object.entries(keyTexts)) {
|
|
31
|
-
if (typeof key !== "string" || !KEY_TEXT.test(key)) throw malformed;
|
|
32
|
-
keys.set(keyId, fromBase64(key));
|
|
33
|
-
}
|
|
34
|
-
if (!keys.has(current)) throw new Error(`${name} has no key for its current key id.`);
|
|
35
|
-
return {
|
|
36
|
-
current,
|
|
37
|
-
keys
|
|
38
|
-
};
|
|
39
|
-
};
|
|
40
|
-
/** A random key id of 12 hexadecimal characters, which is also safe in a variable name. */
|
|
41
|
-
const newKeyId = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
42
|
-
/** A random key of 32 bytes in base64. It needs real randomness, like `sealSecret`. */
|
|
43
|
-
const newKey = () => toBase64(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
44
|
-
const importKey = (ring, keyId) => {
|
|
45
|
-
const bytes = ring.keys.get(keyId);
|
|
46
|
-
if (bytes === void 0) throw new Error(`The key ring has no key "${keyId}".`);
|
|
47
|
-
return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
48
|
-
};
|
|
49
|
-
/** Seals `plaintext` with the current key. `aad` names the owner, so the value opens only there. */
|
|
50
|
-
const sealSecret = async (ring, args) => {
|
|
51
|
-
const key = await importKey(ring, ring.current);
|
|
52
|
-
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
53
|
-
const ciphertext = await crypto.subtle.encrypt({
|
|
54
|
-
name: "AES-GCM",
|
|
55
|
-
iv,
|
|
56
|
-
additionalData: new TextEncoder().encode(args.aad)
|
|
57
|
-
}, key, new TextEncoder().encode(args.plaintext));
|
|
58
|
-
return {
|
|
59
|
-
keyId: ring.current,
|
|
60
|
-
iv: toBase64Url(iv),
|
|
61
|
-
ciphertext: toBase64Url(new Uint8Array(ciphertext))
|
|
62
|
-
};
|
|
63
|
-
};
|
|
64
|
-
/** Opens a sealed value with the key it names. A different `aad` or a changed value fails. */
|
|
65
|
-
const openSecret = async (ring, args) => {
|
|
66
|
-
const { sealed } = args;
|
|
67
|
-
const key = await importKey(ring, sealed.keyId);
|
|
68
|
-
const plaintext = await crypto.subtle.decrypt({
|
|
69
|
-
name: "AES-GCM",
|
|
70
|
-
iv: fromBase64(sealed.iv),
|
|
71
|
-
additionalData: new TextEncoder().encode(args.aad)
|
|
72
|
-
}, key, fromBase64(sealed.ciphertext));
|
|
73
|
-
return new TextDecoder().decode(plaintext);
|
|
74
|
-
};
|
|
75
|
-
//#endregion
|
|
76
|
-
export { sealSecret as a, parseKeyRing as i, newKeyId as n, openSecret as r, newKey as t };
|
|
77
|
-
|
|
78
|
-
//# sourceMappingURL=sealedSecret-B7HlvIg2.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sealedSecret-B7HlvIg2.js","names":[],"sources":["../src/store/sealedSecret.ts"],"sourcesContent":["// AES-256-GCM sealing under a key ring, with Web Crypto only, so that it runs in Convex and in Node.\n//\n// A key ring is the JSON text `{\"current\":\"<keyId>\",\"keys\":{\"<keyId>\":\"<base64 of 32 bytes>\"}}`,\n// which a deployment keeps in one environment variable. `sealSecret` seals with the `current` key.\n// `openSecret` opens with the key that the sealed object names, so an old key stays in the ring\n// until a reseal moves its values to the current key.\n//\n// Seal only where randomness is real: in a Convex action, or outside Convex. In a Convex query or\n// mutation `crypto.getRandomValues` is a seeded deterministic generator, and a repeated IV under one\n// key breaks AES-GCM. Opening draws no randomness, so a query can open.\n\n/** A value sealed with AES-256-GCM under the key `keyId` of a key ring. */\nexport interface SealedSecret {\n readonly keyId: string;\n /** 12 random bytes, base64url. */\n readonly iv: string;\n /** The AES-GCM output with its 16-byte tag, base64url. */\n readonly ciphertext: string;\n}\n\nexport interface KeyRing {\n readonly current: string;\n readonly keys: ReadonlyMap<string, Uint8Array<ArrayBuffer>>;\n}\n\nconst toBase64 = (bytes: Uint8Array) =>\n btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\"\"));\n\nconst toBase64Url = (bytes: Uint8Array) =>\n toBase64(bytes).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n\n/** The bytes of base64 or base64url text. */\nconst fromBase64 = (text: string) => {\n const standard = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const padded = standard.padEnd(standard.length + ((4 - (standard.length % 4)) % 4), \"=\");\n return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));\n};\n\n/** A key of 32 bytes in base64 is 43 characters and one `=`. */\nconst KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;\n\n/**\n * The key ring in the text of the variable `name`. It fails closed when the text is missing or\n * malformed, or when the current key id has no key. An error never quotes the text, which holds\n * the keys.\n */\nexport const parseKeyRing = (name: string, text: string | undefined): KeyRing => {\n let value: unknown;\n try {\n value = JSON.parse(text ?? \"\");\n } catch {\n throw new Error(`${name} is missing or is not JSON.`);\n }\n const malformed = new Error(\n `${name} must be {\"current\":\"<keyId>\",\"keys\":{\"<keyId>\":\"<base64 of 32 bytes>\"}}.`,\n );\n if (typeof value !== \"object\" || value === null) throw malformed;\n if (!(\"current\" in value) || !(\"keys\" in value)) throw malformed;\n const { current, keys: keyTexts } = value;\n if (typeof current !== \"string\" || typeof keyTexts !== \"object\" || keyTexts === null) {\n throw malformed;\n }\n const keys = new Map<string, Uint8Array<ArrayBuffer>>();\n for (const [keyId, key] of Object.entries(keyTexts)) {\n if (typeof key !== \"string\" || !KEY_TEXT.test(key)) throw malformed;\n keys.set(keyId, fromBase64(key));\n }\n if (!keys.has(current)) throw new Error(`${name} has no key for its current key id.`);\n return { current, keys };\n};\n\n/** A random key id of 12 hexadecimal characters, which is also safe in a variable name. */\nexport const newKeyId = (): string =>\n Array.from(crypto.getRandomValues(new Uint8Array(6)), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n\n/** A random key of 32 bytes in base64. It needs real randomness, like `sealSecret`. */\nexport const newKey = (): string => toBase64(crypto.getRandomValues(new Uint8Array(32)));\n\nconst importKey = (ring: KeyRing, keyId: string) => {\n const bytes = ring.keys.get(keyId);\n if (bytes === undefined) throw new Error(`The key ring has no key \"${keyId}\".`);\n return crypto.subtle.importKey(\"raw\", bytes, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]);\n};\n\n/** Seals `plaintext` with the current key. `aad` names the owner, so the value opens only there. */\nexport const sealSecret = async (\n ring: KeyRing,\n args: { readonly plaintext: string; readonly aad: string },\n): Promise<SealedSecret> => {\n const key = await importKey(ring, ring.current);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: new TextEncoder().encode(args.aad) },\n key,\n new TextEncoder().encode(args.plaintext),\n );\n return {\n keyId: ring.current,\n iv: toBase64Url(iv),\n ciphertext: toBase64Url(new Uint8Array(ciphertext)),\n };\n};\n\n/** Opens a sealed value with the key it names. A different `aad` or a changed value fails. */\nexport const openSecret = async (\n ring: KeyRing,\n args: { readonly sealed: SealedSecret; readonly aad: string },\n): Promise<string> => {\n const { sealed } = args;\n const key = await importKey(ring, sealed.keyId);\n const plaintext = await crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: fromBase64(sealed.iv),\n additionalData: new TextEncoder().encode(args.aad),\n },\n key,\n fromBase64(sealed.ciphertext),\n );\n return new TextDecoder().decode(plaintext);\n};\n"],"mappings":";AAyBA,MAAM,YAAY,UAChB,KAAK,MAAM,KAAK,QAAQ,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AAEtE,MAAM,eAAe,UACnB,SAAS,KAAK,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;;AAG7E,MAAM,cAAc,SAAiB;CACnC,MAAM,WAAW,KAAK,WAAW,KAAK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