unoverse 0.1.223 → 0.1.225
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 +0 -1
- package/bin/unoverse.mjs +14 -41
- package/lib/workspace.mjs +2 -2
- package/operator/lib/db-verify.sh +4 -1
- package/operator/lib/help.sh +11 -6
- package/package.json +1 -1
- package/vendor/base/items/collect.js +36 -0
- package/vendor/base/lint/design/vocabulary.mjs +11 -1
- package/vendor/base/lint/nodes/_schema/api.schema.json +75 -0
- package/vendor/base/lint/objects/_schema/agents/agent.schema.json +1 -1
- package/vendor/base/lint/objects/_schema/objects/dataset.schema.json +1 -0
- package/vendor/base/lint/objects/index.mjs +48 -0
- package/lib/login.mjs +0 -274
- package/lib/session.mjs +0 -100
package/README.md
CHANGED
|
@@ -21,7 +21,6 @@ unoverse start # run it (--pull for the latest images)
|
|
|
21
21
|
unoverse check # is it healthy
|
|
22
22
|
unoverse logs # what is it doing
|
|
23
23
|
unoverse where # its addresses, local and deployed, probed live
|
|
24
|
-
unoverse deploy # ship it to your server
|
|
25
24
|
unoverse stop
|
|
26
25
|
```
|
|
27
26
|
|
package/bin/unoverse.mjs
CHANGED
|
@@ -44,7 +44,9 @@ function findUniverse() {
|
|
|
44
44
|
|
|
45
45
|
/** Run an operator command in the universe we are standing in. */
|
|
46
46
|
function operator(u, args) {
|
|
47
|
-
|
|
47
|
+
// UNOVERSE_CLI tells the operator's help it is printed by the CLI, which no longer lists the
|
|
48
|
+
// VM deploy commands (they stay in the runbook, scripts/operator.sh).
|
|
49
|
+
const r = spawnSync("bash", [u.script, ...args], { stdio: "inherit", cwd: u.root, env: { ...process.env, UNOVERSE_CLI: "1" } });
|
|
48
50
|
process.exit(r.status ?? 0);
|
|
49
51
|
}
|
|
50
52
|
|
|
@@ -58,14 +60,19 @@ const UNIVERSE = findUniverse();
|
|
|
58
60
|
// type it to update the CLI far more often than to refresh a local universe's images,
|
|
59
61
|
// and that refresh now belongs to `start --pull`.
|
|
60
62
|
const OPERATOR_COMMANDS = new Set([
|
|
61
|
-
"start", "stop", "check", "logs", "
|
|
63
|
+
"start", "stop", "check", "logs", "db-allow",
|
|
62
64
|
// kept working, not advertised. `publish` is NOT here: it has its own case below,
|
|
63
65
|
// because ONE VERB serves two lanes and the folder decides which (LOCAL_STUDIO.md
|
|
64
66
|
// §Publish is terminal-only) — an asset workspace publishes item rows, a universe
|
|
65
67
|
// publishes the platform via the operator.
|
|
66
|
-
"
|
|
68
|
+
"dev", "build",
|
|
67
69
|
]);
|
|
68
70
|
|
|
71
|
+
// DEPLOYING A UNIVERSE TO A VM IS RETIRED FROM THE CLI (owner, 2026-11-13). The platform ships as
|
|
72
|
+
// cells on Kubernetes (docs/saas-architecture) and a developer's work ships by a push to the org's
|
|
73
|
+
// Git repo. The runbook for a universe still on a VM stays in the platform repo, scripts/operator.sh.
|
|
74
|
+
// `deploy`, `destroy` and `ground` answer with that, in their own case below.
|
|
75
|
+
|
|
69
76
|
const [, , cmd, ...args] = process.argv;
|
|
70
77
|
|
|
71
78
|
// FIRST CONTACT. Someone who has never seen this reads it, so it answers two questions
|
|
@@ -97,10 +104,6 @@ const HELP = [
|
|
|
97
104
|
` ${bold("After that")}`,
|
|
98
105
|
row("studio", "Design components, nodes and agent skills"),
|
|
99
106
|
row("lint", "Check your components, nodes and skills, the same way your universe does"),
|
|
100
|
-
row("deploy", "Put a universe on a cloud"),
|
|
101
|
-
` ${dim("deploy aws your universe → AWS")}`,
|
|
102
|
-
` ${dim("deploy digitalocean your universe → DigitalOcean")}`,
|
|
103
|
-
row("login", "Sign in to a universe (deploy asks by itself when needed)"),
|
|
104
107
|
row("update", "Update this CLI"),
|
|
105
108
|
"",
|
|
106
109
|
].join("\n");
|
|
@@ -251,40 +254,10 @@ switch (cmd) {
|
|
|
251
254
|
break;
|
|
252
255
|
}
|
|
253
256
|
|
|
254
|
-
case "
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
let target = args[0];
|
|
259
|
-
if (!target) {
|
|
260
|
-
// No URL typed: the workspace's committed target is the obvious answer.
|
|
261
|
-
const { findWorkspace, readConfig } = await import("../lib/workspace.mjs");
|
|
262
|
-
const ws = findWorkspace();
|
|
263
|
-
if (ws?.kind === "assets" || ws?.kind === "org") target = (await readConfig(ws.root)).universe;
|
|
264
|
-
}
|
|
265
|
-
if (!target) {
|
|
266
|
-
console.error(`\n Which universe? unoverse login <url>\n ${dim("(or run it from a workspace whose unoverse.yaml names one)")}\n`);
|
|
267
|
-
process.exit(1);
|
|
268
|
-
}
|
|
269
|
-
try {
|
|
270
|
-
await login(normaliseUrl(target));
|
|
271
|
-
} catch (e) {
|
|
272
|
-
console.error(`\n ✗ ${e.message}\n`);
|
|
273
|
-
process.exit(1);
|
|
274
|
-
}
|
|
275
|
-
break;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
case "deploy": {
|
|
279
|
-
// THE OPERATOR'S CLOUD DEPLOY: puts a universe on a cloud. A developer's own work never
|
|
280
|
-
// ships this way; it reaches a universe through the org's Git repo (RELEASE_LIFECYCLE.md §3).
|
|
281
|
-
// A word that is not a cloud is refused here, before the operator runs anything.
|
|
282
|
-
if (args[0] && !args[0].startsWith("-") && !["aws", "amazon", "digitalocean", "do"].includes(args[0])) {
|
|
283
|
-
console.log(`\n 'deploy ${args[0]}' is not a cloud. Use: unoverse deploy aws, or unoverse deploy digitalocean.\n Your own work ships by a push to your org's Git repo.\n`);
|
|
284
|
-
process.exit(1);
|
|
285
|
-
}
|
|
286
|
-
if (UNIVERSE) operator(UNIVERSE, ["deploy", ...args]);
|
|
287
|
-
console.log(`\n '${["deploy", args[0]].filter(Boolean).join(" ")}' operates a universe, and this folder is not one.\n cd into your universe. To ship your own work, push it to your org's Git repo.\n`);
|
|
257
|
+
case "deploy":
|
|
258
|
+
case "destroy":
|
|
259
|
+
case "ground": {
|
|
260
|
+
console.log(`\n '${cmd}' is retired from the CLI. The platform ships as cells on Kubernetes,\n and your own work ships by a push to your org's Git repo.\n ${dim("A universe still on a VM: the runbook is scripts/operator.sh in the platform repo.")}\n`);
|
|
288
261
|
process.exit(1);
|
|
289
262
|
}
|
|
290
263
|
|
package/lib/workspace.mjs
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* `unoverse.yaml` at the workspace root is the COMMITTED project config: `universe:`, the
|
|
10
10
|
* default deploy target, and `environments:`, named targets (`uat`, `production`) that CI
|
|
11
11
|
* picks with `--env`. It is config, not a secret: the whole team and CI deploy to the same
|
|
12
|
-
* places, which is exactly why it belongs in the repo. Credentials never live here
|
|
13
|
-
*
|
|
12
|
+
* places, which is exactly why it belongs in the repo. Credentials never live here, and the
|
|
13
|
+
* CLI holds none: work ships by a push to the org's Git repo, so Git decides who may ship.
|
|
14
14
|
*/
|
|
15
15
|
import { existsSync, renameSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
16
|
import { join, resolve } from "node:path";
|
|
@@ -56,6 +56,9 @@ cmd_db_verify() {
|
|
|
56
56
|
credentials: [
|
|
57
57
|
"id", "name", "type", "scope", "data", "created_at", "updated_at", "ref", "org", "copied_from"
|
|
58
58
|
],
|
|
59
|
+
credential_links: [
|
|
60
|
+
"credential_id", "org", "linked_by", "linked_at"
|
|
61
|
+
],
|
|
59
62
|
token_usage: [
|
|
60
63
|
"id", "workflow_id", "execution_id", "node_id", "node_type",
|
|
61
64
|
"model", "usage", "timestamp", "created_at", "user_id"
|
|
@@ -207,7 +210,7 @@ cmd_db_verify() {
|
|
|
207
210
|
],
|
|
208
211
|
agent_runs: [
|
|
209
212
|
"run_id", "agent_ref", "woken_by", "instruction", "state", "outcome",
|
|
210
|
-
"started_at", "ended_at"
|
|
213
|
+
"started_at", "ended_at", "org", "conversation"
|
|
211
214
|
],
|
|
212
215
|
dictionary_mentions: [
|
|
213
216
|
"id", "org", "job_id", "source", "object_type", "fields", "document_id",
|
package/operator/lib/help.sh
CHANGED
|
@@ -16,10 +16,13 @@ cmd_help() {
|
|
|
16
16
|
echo -e " ${BOLD}Anywhere${NC}"
|
|
17
17
|
echo -e " ${GREEN}create${NC} Start something new, here"
|
|
18
18
|
echo -e " ${GREEN}studio${NC} Author components, nodes, agent skills"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
# THE VM DEPLOY COMMANDS ARE THE RUNBOOK'S ONLY (owner, 2026-11-13): the CLI no longer runs
|
|
20
|
+
# them (it sets UNOVERSE_CLI), so its help does not list them; scripts/operator.sh still does.
|
|
21
|
+
if [ -z "${UNOVERSE_CLI:-}" ]; then
|
|
22
|
+
echo -e " ${GREEN}deploy${NC} Put a universe on a cloud"
|
|
23
|
+
echo -e " ${DIM}deploy aws your universe → AWS${NC}"
|
|
24
|
+
echo -e " ${DIM}deploy digitalocean your universe → DigitalOcean${NC}"
|
|
25
|
+
fi
|
|
23
26
|
echo -e " ${GREEN}where${NC} Links to your universe ${DIM}(Canvas, API), checked live${NC}"
|
|
24
27
|
echo -e " ${GREEN}update${NC} Update this CLI"
|
|
25
28
|
echo ""
|
|
@@ -34,8 +37,10 @@ cmd_help() {
|
|
|
34
37
|
# SHOW THE COMMAND, not a description of it. "aws or digitalocean" told a reader the
|
|
35
38
|
# clouds exist without telling them what to type, so the shape of the command still had
|
|
36
39
|
# to be guessed. Print the line they will actually run.
|
|
37
|
-
|
|
38
|
-
|
|
40
|
+
if [ -z "${UNOVERSE_CLI:-}" ]; then
|
|
41
|
+
echo -e " ${GREEN}destroy${NC} Take it down ${DIM}(shows what goes, and what stays)${NC}"
|
|
42
|
+
echo -e " ${DIM}destroy aws · destroy digitalocean${NC}"
|
|
43
|
+
fi
|
|
39
44
|
echo -e " ${GREEN}db-allow${NC} Let this machine reach the database ${DIM}(run it when you change network)${NC}"
|
|
40
45
|
echo ""
|
|
41
46
|
# Owner-only lane. Printed ONLY when publish.sh is present, so a starter kit never
|
package/package.json
CHANGED
|
@@ -55,6 +55,42 @@ export function readOrgName(dir) {
|
|
|
55
55
|
return null;
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* DOES THIS ORG OFFER ITS AGENTS to other orgs as a team (docs/unoverseCopilot/ORG_BUILDER.md § 0c;
|
|
60
|
+
* owner, 2026-11-15: "should be part of the org yaml, not a switch")? Only `marketplace: true` in its
|
|
61
|
+
* unoverse.yaml says yes; absent, or anything else, is no. The line marks a marketplace org, the same
|
|
62
|
+
* whether its team is added on this universe or installed from a remote marketplace (owner,
|
|
63
|
+
* 2026-11-19, who renamed it from `offerAgents`: "its the same flag, no need for both"). Declared in Git, so it changes by a
|
|
64
|
+
* reviewed commit, and no Agent can write it (unoverse.yaml is outside every org folder).
|
|
65
|
+
*/
|
|
66
|
+
export function readOrgOffersAgents(dir) {
|
|
67
|
+
const file = join(dir, "unoverse.yaml");
|
|
68
|
+
if (!existsSync(file))
|
|
69
|
+
return false;
|
|
70
|
+
try {
|
|
71
|
+
return parseYaml(readFileSync(file, "utf8"))?.marketplace === true;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* THE TEAM'S VERSION (docs/unoverseCopilot/ORG_BUILDER.md § 0c, step 2): the one number an org gives
|
|
79
|
+
* its team as a whole, `version: 1.2.3` in its unoverse.yaml, raised by hand in the pull request that
|
|
80
|
+
* releases it. Null when the file gives none, or gives anything that is not three numbers.
|
|
81
|
+
*/
|
|
82
|
+
export function readOrgVersion(dir) {
|
|
83
|
+
const file = join(dir, "unoverse.yaml");
|
|
84
|
+
if (!existsSync(file))
|
|
85
|
+
return null;
|
|
86
|
+
try {
|
|
87
|
+
const version = parseYaml(readFileSync(file, "utf8"))?.version;
|
|
88
|
+
return typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version.trim()) ? version.trim() : null;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
58
94
|
/** This folder as an org repo, or null. */
|
|
59
95
|
export function orgRepo(dir) {
|
|
60
96
|
const org = readOrgName(dir);
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// ── ground truth (mirrors packages/docs/schemas/design/unoverse.schema.json + server guards) ──
|
|
14
14
|
export const PRIMITIVES = new Set([
|
|
15
15
|
"Box", "Stack", "Row", "Column", "Each", "Switch", "ComponentSlot", "Timeline",
|
|
16
|
-
"Text", "Image", "Button", "Input", "Select", "Markdown", "Skeleton", "Icon", "Ref", "Orb", "Template", "Place",
|
|
16
|
+
"Text", "Image", "Button", "Input", "Select", "Markdown", "Skeleton", "Icon", "Ref", "Orb", "TalkingHead", "Spline", "Template", "Place",
|
|
17
17
|
]);
|
|
18
18
|
export const CONDITION_KEYS = new Set(["field", "eq", "ne", "in"]);
|
|
19
19
|
|
|
@@ -82,6 +82,15 @@ export const PRIMITIVE_PROPS = {
|
|
|
82
82
|
Icon: ["icon", "name"],
|
|
83
83
|
Skeleton: ["variant"],
|
|
84
84
|
Orb: ["state", "size"],
|
|
85
|
+
// THE FACE: a talking head that moves its mouth to the voice the page is playing. Its code
|
|
86
|
+
// and files are fetched from the unoverse server the first time one is drawn.
|
|
87
|
+
TalkingHead: ["avatar", "size", "lipsync", "state"],
|
|
88
|
+
// A 3D SCENE made in Spline, drawn by Spline's own player. `src` is the scene's address. Every
|
|
89
|
+
// `bind` key but `src` names a variable in the scene, so it has no fixed bind list (below).
|
|
90
|
+
// Its `action` runs when an object in the scene is pressed, with that object's name as
|
|
91
|
+
// `target`. The player loads the first time one is drawn: from the unoverse server when it
|
|
92
|
+
// carries a copy, otherwise from Spline's own public address.
|
|
93
|
+
Spline: ["src"],
|
|
85
94
|
Button: ["children", "value", "label", "icon", "disabledWhen"],
|
|
86
95
|
Input: ["placeholder", "inputType", "disabledWhen", "maxLength", "multiline", "rows",
|
|
87
96
|
"inputMode", "autoComplete", "advanceOnFill"],
|
|
@@ -106,6 +115,7 @@ export const PRIMITIVE_BINDS = {
|
|
|
106
115
|
Text: ["value"], Image: ["src", "alt"], Markdown: ["value"], Icon: ["name"],
|
|
107
116
|
Button: ["label"], Input: ["value", "placeholder"], Select: ["options", "value"],
|
|
108
117
|
Each: ["items"],
|
|
118
|
+
TalkingHead: ["avatar", "size", "lipsync", "state"],
|
|
109
119
|
};
|
|
110
120
|
// the portable style vocabulary — every key the SDK interpreter maps (sdk/style.ts).
|
|
111
121
|
// Each is a neutral intent every native renderer (iOS/Android/RN/Flutter) implements;
|
|
@@ -927,6 +927,51 @@
|
|
|
927
927
|
},
|
|
928
928
|
"additionalProperties": false
|
|
929
929
|
},
|
|
930
|
+
"conversation": {
|
|
931
|
+
"type": "object",
|
|
932
|
+
"required": [
|
|
933
|
+
"remember",
|
|
934
|
+
"user",
|
|
935
|
+
"assistant"
|
|
936
|
+
],
|
|
937
|
+
"description": "CONVERSATION MEMORY FOR A VENDOR THAT KEEPS NOTHING BETWEEN REQUESTS (Anthropic's Messages API keeps a chat for 5 minutes at most and asks the application to keep its own copy). The same job `continuity` does for a vendor that keeps the chat itself (OpenAI's Responses API). The loop keeps what was said in the conversation, one user message and the final answer per run, and exposes it to the request as `history`, which the manifest spreads ahead of the new message:\n\n messages: history.concat([{ role: 'user', content: config.prompt }]).concat(transcript)\n\nWhat is kept is what was SAID, never a turn's tool calls or thinking, so no earlier turn is replayed in a form the vendor checks.",
|
|
938
|
+
"properties": {
|
|
939
|
+
"remember": {
|
|
940
|
+
"type": "object",
|
|
941
|
+
"required": [
|
|
942
|
+
"key"
|
|
943
|
+
],
|
|
944
|
+
"description": "Where the conversation is held, and whether it is this run. Key on the CONVERSATION, not the turn.",
|
|
945
|
+
"properties": {
|
|
946
|
+
"when": {
|
|
947
|
+
"type": "string",
|
|
948
|
+
"description": "Expression: keep and send the conversation only when this is true (the node's own switch)."
|
|
949
|
+
},
|
|
950
|
+
"key": {
|
|
951
|
+
"type": "string",
|
|
952
|
+
"description": "State key the conversation is held under, templated against the run's scope."
|
|
953
|
+
}
|
|
954
|
+
},
|
|
955
|
+
"additionalProperties": false
|
|
956
|
+
},
|
|
957
|
+
"user": {
|
|
958
|
+
"type": "string",
|
|
959
|
+
"description": "Expression: this run's message from the person, in the vendor's message shape. Has `config` and `scope`."
|
|
960
|
+
},
|
|
961
|
+
"assistant": {
|
|
962
|
+
"type": "string",
|
|
963
|
+
"description": "Expression: the final answer, in the vendor's message shape. Has `text`."
|
|
964
|
+
},
|
|
965
|
+
"keep": {
|
|
966
|
+
"type": [
|
|
967
|
+
"number",
|
|
968
|
+
"string"
|
|
969
|
+
],
|
|
970
|
+
"description": "How many messages to keep, newest last; the oldest fall off whole. Default 40."
|
|
971
|
+
}
|
|
972
|
+
},
|
|
973
|
+
"additionalProperties": false
|
|
974
|
+
},
|
|
930
975
|
"transcript": {
|
|
931
976
|
"type": "object",
|
|
932
977
|
"additionalProperties": false,
|
|
@@ -1007,6 +1052,36 @@
|
|
|
1007
1052
|
},
|
|
1008
1053
|
"additionalProperties": false
|
|
1009
1054
|
},
|
|
1055
|
+
"ask": {
|
|
1056
|
+
"type": "object",
|
|
1057
|
+
"required": [
|
|
1058
|
+
"schema"
|
|
1059
|
+
],
|
|
1060
|
+
"description": "api/ask.yaml — WHAT THE RUN NOW WAITS ON, recorded after the node settles as the run's open question in the MCP tasks extension's own shape: an `elicitation/create` form (`{ message, requestedSchema }`). A client following the task (`subscriptions/listen`, `notifications/tasks`) reads the step from there and answers it with `tasks/update`.\n\nEvaluated over `output` (the connectors this run emitted) plus the usual roots, as `publish` is, so the question recorded is the step the node actually handed out. A run with no id (a headless evaluation) records nothing.",
|
|
1061
|
+
"properties": {
|
|
1062
|
+
"when": {
|
|
1063
|
+
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1064
|
+
"description": "Record the question when true; false clears the one standing. Absent means always."
|
|
1065
|
+
},
|
|
1066
|
+
"message": {
|
|
1067
|
+
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1068
|
+
"description": "The form's message: the text shown with the question. Absent means an empty message."
|
|
1069
|
+
},
|
|
1070
|
+
"schema": {
|
|
1071
|
+
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1072
|
+
"description": "The form's `requestedSchema`. Must evaluate to a plain object; anything else records nothing and clears the question standing."
|
|
1073
|
+
},
|
|
1074
|
+
"wait": {
|
|
1075
|
+
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1076
|
+
"description": "When true, the node is held on this question until the person answers. Absent means the node waits whenever `answer` is declared."
|
|
1077
|
+
},
|
|
1078
|
+
"answer": {
|
|
1079
|
+
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1080
|
+
"description": "What an accept hands back, with the accepted form's content in scope as `answer`. The node runs again with the value as its next collected input. A decline or a cancel stops the task. Without it the node never waits."
|
|
1081
|
+
}
|
|
1082
|
+
},
|
|
1083
|
+
"additionalProperties": false
|
|
1084
|
+
},
|
|
1010
1085
|
"renderComponents": {
|
|
1011
1086
|
"$ref": "_defs.schema.json#/definitions/expression",
|
|
1012
1087
|
"description": "api/renderComponents.yaml — rows to render as content cards on the CALLER'S LIVE SCREEN, e.g. \"return response.results\". The RUN LANE'S card lane, the same renderer the service channel's per-method `renderComponents` uses: a row carrying a component app (metadata.app) draws its card the moment the node settles. Data-driven, never a model tool.\n\nEvaluated AFTER the events table, over the FULL settled reply (`response` is the final call's payload; `output` and `calls` are also in scope), because a card needs the full row (component uri, images, authored copy) that an events projection strips.\n\nFire-and-forget: a card is a side channel to a screen and must not hold up the graph. With no live session (builder, tests, headless, cron) it no-ops on the missing session id, so a manifest declaring it stays pure wherever it is not wanted, with no flag to juggle."
|
|
@@ -124,7 +124,7 @@
|
|
|
124
124
|
"type": "array",
|
|
125
125
|
"items": {
|
|
126
126
|
"type": "string",
|
|
127
|
-
"pattern": "^unoverse://tasks/[a-z0-9][a-z0-9-]*/[A-Za-z0-9][A-Za-z0-9._-]
|
|
127
|
+
"pattern": "^unoverse://(tasks/[a-z0-9][a-z0-9-]*/[A-Za-z0-9][A-Za-z0-9._-]*|agents/[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*)$"
|
|
128
128
|
},
|
|
129
129
|
"description": "The tasks it may call, each by its one URI. A marketplace MCP is a task too: unoverse://tasks/marketplace/signal-save hands over every tool it offers (MCP_TASKS.md § 2a)."
|
|
130
130
|
},
|
|
@@ -113,6 +113,7 @@
|
|
|
113
113
|
"part": { "type": "object", "required": ["object", "column", "level", "name", "of"], "properties": { "object": { "type": "string" }, "column": { "type": "string" }, "level": { "type": "string" }, "name": { "type": "string" }, "of": { "type": "string" } }, "description": "Its parts (a fund's share classes): their object, column, `level` value, name field and the field naming their subject." },
|
|
114
114
|
"none": { "type": "string", "description": "The `level` value for a document about no subject (market)." },
|
|
115
115
|
"relative": { "type": "array", "items": { "type": "string" }, "description": "The measures that are a subject's figure against its comparison (excess return: the return above the benchmark's): a row of one that names no subject of its own is the subject the table's own rows name, when they name exactly one; with two or more it names none. Each is one of the measure column's `enum`." },
|
|
116
|
+
"held": { "type": "string", "description": "The measure a list of what the subject holds states for each position (exposure): a percentage column of such a list that no word names is each position's figure of it. Absent, none is assumed." },
|
|
116
117
|
"vehicles": { "type": "array", "items": { "type": "string" }, "description": "The words a name of the subject's kind carries when it names one (fund; a segregated portfolio's portfolio): an allocation table's row whose name holds one of them, with words of its own, is a holding, a line from the subject to it (pipelines/tables.md 3c rule 3); a row of words alone is a heading. Absent, the word fund." },
|
|
117
118
|
"terms": { "type": "array", "items": { "type": "string" }, "description": "The measures that are a record's standing terms, never figures over time (fee): a rate of one is a field of the subject's or part's record, read by the layout, and never a row; an amount of money of one (fees charged over a period) stays a row. Each is one of the measure column's `enum`." }
|
|
118
119
|
}
|
|
@@ -426,6 +426,13 @@ export function lintObjects(designRoot, options = {}) {
|
|
|
426
426
|
if (ch.node) report("error", at, `agent ${name}: the spatial trigger names no node; the Agent is found in its org's Spatial`);
|
|
427
427
|
continue;
|
|
428
428
|
}
|
|
429
|
+
// TALKED TO BY A2A (docs/architecture/signal/AGENTS.md § 5a): the platform's own door serves it,
|
|
430
|
+
// so it names no node. Its Agent Card must say a version (A2A § 4.4.1), so its file must.
|
|
431
|
+
if (ch.name === "a2a") {
|
|
432
|
+
if (ch.node) report("error", at, `agent ${name}: the a2a trigger names no node; the platform serves A2A itself`);
|
|
433
|
+
if (typeof doc.version !== "string" || !doc.version.trim()) report("error", at, `agent ${name}: the a2a trigger needs a version in its file, for its Agent Card`);
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
429
436
|
if (!ch.node) report("error", at, `agent ${name}: trigger ${ch.name} names no node`);
|
|
430
437
|
else if (nodes && !nodes.has(ch.node)) report("error", at, `agent ${name}: trigger ${ch.name} names node ${ch.node}, which is not a node here`);
|
|
431
438
|
}
|
|
@@ -458,6 +465,47 @@ export function lintObjects(designRoot, options = {}) {
|
|
|
458
465
|
}
|
|
459
466
|
}
|
|
460
467
|
|
|
468
|
+
/**
|
|
469
|
+
* A STEP'S SKILL IS IN THE ORG (docs.unoverse.ai/design/tasks, "A step carries its skill"). A
|
|
470
|
+
* step of a template or a component may name the skill its caller follows, `skill: skills/<name>`:
|
|
471
|
+
* a path in the task's own org, never a full address. The skill must be there, in the org's
|
|
472
|
+
* skills/ or the marketplace's, or the step would hand out an address nothing answers.
|
|
473
|
+
*/
|
|
474
|
+
for (const tier of tiers) {
|
|
475
|
+
if (!tier.org) continue;
|
|
476
|
+
for (const kind of ["templates", "components"]) {
|
|
477
|
+
for (const n of foldersIn(tier.dir, kind)) {
|
|
478
|
+
const file = join(tier.dir, kind, n, `${n}.yaml`);
|
|
479
|
+
const doc = readYaml(file);
|
|
480
|
+
if (!isRecord(doc) || !isRecord(doc.states)) continue;
|
|
481
|
+
for (const [stateName, state] of Object.entries(doc.states)) {
|
|
482
|
+
if (!isRecord(state) || !isRecord(state.states)) continue;
|
|
483
|
+
for (const [stepName, step] of Object.entries(state.states)) {
|
|
484
|
+
if (!isRecord(step)) continue;
|
|
485
|
+
const where = `task ${tier.org}/${n}: step ${stateName}.${stepName}`;
|
|
486
|
+
// A STEP'S LISTED ANSWERS ARE THE TASK'S OWN ("A step asks only its own answers"): each
|
|
487
|
+
// name in `asks` is one of the task's `outputs`, or the step asks for nothing anyone declared.
|
|
488
|
+
if (step.asks !== undefined) {
|
|
489
|
+
const declared = isRecord(doc.outputs) ? Object.keys(doc.outputs) : [];
|
|
490
|
+
if (!Array.isArray(step.asks) || step.asks.some((k) => typeof k !== "string")) {
|
|
491
|
+
report("error", rel(file), `${where} lists its answers as ${JSON.stringify(step.asks)}; write a list of output names, asks: [name, name]`);
|
|
492
|
+
} else {
|
|
493
|
+
for (const k of step.asks) if (!declared.includes(k)) report("error", rel(file), `${where} asks for "${k}", which is not one of the task's outputs`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (step.skill === undefined) continue;
|
|
497
|
+
const m = typeof step.skill === "string" ? /^skills\/([a-z0-9][a-z0-9-]*)$/.exec(step.skill) : null;
|
|
498
|
+
if (!m) {
|
|
499
|
+
report("error", rel(file), `${where} names its skill as ${JSON.stringify(step.skill)}; write it as a path in the org, skill: skills/<name>`);
|
|
500
|
+
} else if (!existsSync(join(tier.dir, "skills", m[1], "SKILL.md")) && !existsSync(join(marketplace, "skills", m[1], "SKILL.md"))) {
|
|
501
|
+
report("error", rel(file), `${where} names the skill "${m[1]}", which is not in skills/`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
461
509
|
const rank = { error: 0, warn: 1, hint: 2 };
|
|
462
510
|
const sorted = [...problems].sort((a, b) => rank[a.level] - rank[b.level] || a.file.localeCompare(b.file));
|
|
463
511
|
return { problems: sorted, objectCount, pipelineCount, agentCount, designRoot: ROOT };
|
package/lib/login.mjs
DELETED
|
@@ -1,274 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* unoverse login — the Stripe-shaped browser handshake.
|
|
3
|
-
*
|
|
4
|
-
* A UNIVERSE NAMES ITS OWN IDENTITY PROVIDER. Nothing here hardcodes an issuer or a
|
|
5
|
-
* vendor: the CLI asks the universe at /.well-known/unoverse-universe, then asks that
|
|
6
|
-
* issuer's own /.well-known/openid-configuration for its endpoints. Auth0, Cognito,
|
|
7
|
-
* Okta, Entra and Keycloak all answer the second document, which is why the flow is
|
|
8
|
-
* Authorization Code + PKCE with a loopback redirect and NOT the device flow (Cognito
|
|
9
|
-
* has no device flow; every OIDC provider has this).
|
|
10
|
-
*
|
|
11
|
-
* THE CALLBACK PORT IS FIXED (4109) because IdPs match redirect URIs exactly — an
|
|
12
|
-
* ephemeral port could never be registered. 4109 continues the platform's sequence
|
|
13
|
-
* (4105 public listener, 4106 runtime, 4107 unoverse-runtime, 4108 Studio) and is held
|
|
14
|
-
* only for the seconds the browser takes. ground.sh registers it as an allowed callback.
|
|
15
|
-
*
|
|
16
|
-
* This is the ONLY human authentication on the platform (LOCAL_STUDIO.md §Publish is
|
|
17
|
-
* terminal-only). Keys are for CI; humans get a browser and their normal account.
|
|
18
|
-
*/
|
|
19
|
-
import { createServer } from "node:http";
|
|
20
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
21
|
-
import { spawn } from "node:child_process";
|
|
22
|
-
import { getSession, saveSession, freshToken } from "./session.mjs";
|
|
23
|
-
|
|
24
|
-
export const DISCOVERY_PATH = "/.well-known/unoverse-universe";
|
|
25
|
-
export const CALLBACK_PORT = 4109;
|
|
26
|
-
const CALLBACK_URL = `http://127.0.0.1:${CALLBACK_PORT}/callback`;
|
|
27
|
-
const LOGIN_TIMEOUT_MS = 300_000;
|
|
28
|
-
|
|
29
|
-
/** What a developer typed → an origin. Mirrors studio's universes.ts. */
|
|
30
|
-
export function normaliseUrl(input) {
|
|
31
|
-
const trimmed = (input ?? "").trim();
|
|
32
|
-
if (!trimmed) throw new Error("Enter a universe address");
|
|
33
|
-
const isLocal = /^(https?:\/\/)?(localhost|127\.0\.0\.1)(:|\/|$)/i.test(trimmed);
|
|
34
|
-
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `${isLocal ? "http" : "https"}://${trimmed}`;
|
|
35
|
-
let parsed;
|
|
36
|
-
try {
|
|
37
|
-
parsed = new URL(withScheme);
|
|
38
|
-
} catch {
|
|
39
|
-
throw new Error(`"${input}" is not a valid address`);
|
|
40
|
-
}
|
|
41
|
-
return parsed.origin;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Ask a universe how to log in. Failure is the common case (wrong address, universe
|
|
46
|
-
* down, a plain website), and each gets a message a developer can act on.
|
|
47
|
-
*/
|
|
48
|
-
export async function discover(origin) {
|
|
49
|
-
let response;
|
|
50
|
-
try {
|
|
51
|
-
response = await fetch(`${origin}${DISCOVERY_PATH}`, { headers: { accept: "application/json" } });
|
|
52
|
-
} catch {
|
|
53
|
-
throw new Error(`Could not reach ${origin}. Check the address, and that the universe is running.`);
|
|
54
|
-
}
|
|
55
|
-
if (response.status === 404) throw new Error(`Something answered at ${origin}, but it is not a universe.`);
|
|
56
|
-
if (!response.ok) throw new Error(`${origin} answered with an error (${response.status}).`);
|
|
57
|
-
let body;
|
|
58
|
-
try {
|
|
59
|
-
body = await response.json();
|
|
60
|
-
} catch {
|
|
61
|
-
throw new Error(`${origin} answered, but not like a universe. If it is one, it may need restarting.`);
|
|
62
|
-
}
|
|
63
|
-
if (typeof body?.authEnabled !== "boolean") {
|
|
64
|
-
throw new Error(`${origin} answered, but not like a universe. If it is one, it may need restarting.`);
|
|
65
|
-
}
|
|
66
|
-
return {
|
|
67
|
-
authEnabled: body.authEnabled,
|
|
68
|
-
issuer: body.issuer ?? null,
|
|
69
|
-
clientId: body.clientId ?? null,
|
|
70
|
-
audience: body.audience ?? null,
|
|
71
|
-
publishPermission: body.publishPermission ?? "marketplace:publish",
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** The issuer's own endpoint document. Standard OIDC; both Auth0 and Cognito serve it. */
|
|
76
|
-
export async function oidcEndpoints(issuer) {
|
|
77
|
-
const base = issuer.replace(/\/+$/, "");
|
|
78
|
-
let response;
|
|
79
|
-
try {
|
|
80
|
-
response = await fetch(`${base}/.well-known/openid-configuration`, { headers: { accept: "application/json" } });
|
|
81
|
-
} catch {
|
|
82
|
-
throw new Error(`Could not reach the identity provider at ${issuer}.`);
|
|
83
|
-
}
|
|
84
|
-
if (!response.ok) throw new Error(`The identity provider at ${issuer} answered with an error (${response.status}).`);
|
|
85
|
-
const doc = await response.json();
|
|
86
|
-
if (!doc?.authorization_endpoint || !doc?.token_endpoint) {
|
|
87
|
-
throw new Error(`${issuer} does not serve a usable OpenID configuration.`);
|
|
88
|
-
}
|
|
89
|
-
return doc;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
93
|
-
|
|
94
|
-
/** Best effort; the URL is always printed so a developer can click it themselves. */
|
|
95
|
-
function openBrowser(url) {
|
|
96
|
-
const [cmd, args] =
|
|
97
|
-
process.platform === "darwin" ? ["open", [url]]
|
|
98
|
-
: process.platform === "win32" ? ["cmd", ["/c", "start", "", url.replace(/&/g, "^&")]]
|
|
99
|
-
: ["xdg-open", [url]];
|
|
100
|
-
try {
|
|
101
|
-
spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
|
|
102
|
-
} catch {
|
|
103
|
-
/* the printed URL is the fallback */
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** The email inside an id_token, display-only. No verification: nothing trusts it. */
|
|
108
|
-
function emailFrom(idToken) {
|
|
109
|
-
try {
|
|
110
|
-
return JSON.parse(Buffer.from(idToken.split(".")[1], "base64url").toString())?.email ?? null;
|
|
111
|
-
} catch {
|
|
112
|
-
return null;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** One loopback round trip: resolves {code} once the browser lands on /callback. */
|
|
117
|
-
function waitForCallback(state) {
|
|
118
|
-
return new Promise((resolvePromise, rejectPromise) => {
|
|
119
|
-
const server = createServer((req, res) => {
|
|
120
|
-
const url = new URL(req.url, `http://127.0.0.1:${CALLBACK_PORT}`);
|
|
121
|
-
if (url.pathname !== "/callback") {
|
|
122
|
-
res.writeHead(404).end();
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
const finish = (title, body) => {
|
|
126
|
-
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
127
|
-
res.end(`<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0"><div style="text-align:center"><h1>${title}</h1><p>${body}</p></div>`);
|
|
128
|
-
};
|
|
129
|
-
const err = url.searchParams.get("error");
|
|
130
|
-
if (err) {
|
|
131
|
-
finish("Sign-in failed", url.searchParams.get("error_description") ?? err);
|
|
132
|
-
cleanup();
|
|
133
|
-
rejectPromise(new Error(`The identity provider refused: ${url.searchParams.get("error_description") ?? err}`));
|
|
134
|
-
return;
|
|
135
|
-
}
|
|
136
|
-
if (url.searchParams.get("state") !== state) {
|
|
137
|
-
finish("Sign-in failed", "State mismatch. Close this tab and run the command again.");
|
|
138
|
-
cleanup();
|
|
139
|
-
rejectPromise(new Error("Login state mismatch — the response did not come from this login attempt."));
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
finish("You're signed in", "Return to the terminal.");
|
|
143
|
-
cleanup();
|
|
144
|
-
resolvePromise({ code: url.searchParams.get("code") });
|
|
145
|
-
});
|
|
146
|
-
const timer = setTimeout(() => {
|
|
147
|
-
cleanup();
|
|
148
|
-
rejectPromise(new Error("Login timed out after 5 minutes. Run the command again."));
|
|
149
|
-
}, LOGIN_TIMEOUT_MS);
|
|
150
|
-
function cleanup() {
|
|
151
|
-
clearTimeout(timer);
|
|
152
|
-
server.close();
|
|
153
|
-
}
|
|
154
|
-
server.on("error", (e) => {
|
|
155
|
-
cleanup();
|
|
156
|
-
rejectPromise(
|
|
157
|
-
e.code === "EADDRINUSE"
|
|
158
|
-
? new Error(`Port ${CALLBACK_PORT} is in use (another login in progress?). Free it and retry.`)
|
|
159
|
-
: e,
|
|
160
|
-
);
|
|
161
|
-
});
|
|
162
|
-
server.listen(CALLBACK_PORT, "127.0.0.1");
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Interactive login to one universe. Returns { origin, accessToken, email }.
|
|
168
|
-
* The session is stored for next time; publish calls this only when no session is live.
|
|
169
|
-
*/
|
|
170
|
-
export async function login(universeInput, { log = console.log } = {}) {
|
|
171
|
-
const origin = normaliseUrl(universeInput);
|
|
172
|
-
const config = await discover(origin);
|
|
173
|
-
|
|
174
|
-
if (!config.authEnabled) {
|
|
175
|
-
throw new Error(
|
|
176
|
-
`${origin} has authentication switched off, so there is no account to sign in with.\n` +
|
|
177
|
-
` To deploy there, set UNOVERSE_TOKEN to a publish key minted on the universe itself.`,
|
|
178
|
-
);
|
|
179
|
-
}
|
|
180
|
-
if (!config.issuer) throw new Error(`${origin} has no identity provider configured.`);
|
|
181
|
-
if (!config.clientId) throw new Error(`${origin} has no client id configured for sign-in.`);
|
|
182
|
-
|
|
183
|
-
const endpoints = await oidcEndpoints(config.issuer);
|
|
184
|
-
|
|
185
|
-
const verifier = b64url(randomBytes(32));
|
|
186
|
-
const challenge = b64url(createHash("sha256").update(verifier).digest());
|
|
187
|
-
const state = b64url(randomBytes(16));
|
|
188
|
-
|
|
189
|
-
// offline_access only where the IdP declares it (Auth0 needs it for a refresh token;
|
|
190
|
-
// Cognito does not know the scope and refuses requests that name it).
|
|
191
|
-
const scopes = ["openid", "profile", "email"];
|
|
192
|
-
if ((endpoints.scopes_supported ?? []).includes("offline_access")) scopes.push("offline_access");
|
|
193
|
-
|
|
194
|
-
const authUrl = new URL(endpoints.authorization_endpoint);
|
|
195
|
-
authUrl.search = new URLSearchParams({
|
|
196
|
-
response_type: "code",
|
|
197
|
-
client_id: config.clientId,
|
|
198
|
-
redirect_uri: CALLBACK_URL,
|
|
199
|
-
scope: scopes.join(" "),
|
|
200
|
-
state,
|
|
201
|
-
code_challenge: challenge,
|
|
202
|
-
code_challenge_method: "S256",
|
|
203
|
-
...(config.audience ? { audience: config.audience } : {}),
|
|
204
|
-
}).toString();
|
|
205
|
-
|
|
206
|
-
const pending = waitForCallback(state);
|
|
207
|
-
log(`\n Opening your browser to sign in to ${origin}`);
|
|
208
|
-
log(` If it does not open: ${authUrl.href}\n`);
|
|
209
|
-
openBrowser(authUrl.href);
|
|
210
|
-
|
|
211
|
-
const { code } = await pending;
|
|
212
|
-
|
|
213
|
-
const exchange = await fetch(endpoints.token_endpoint, {
|
|
214
|
-
method: "POST",
|
|
215
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
216
|
-
body: new URLSearchParams({
|
|
217
|
-
grant_type: "authorization_code",
|
|
218
|
-
client_id: config.clientId,
|
|
219
|
-
code,
|
|
220
|
-
redirect_uri: CALLBACK_URL,
|
|
221
|
-
code_verifier: verifier,
|
|
222
|
-
}),
|
|
223
|
-
});
|
|
224
|
-
if (!exchange.ok) {
|
|
225
|
-
throw new Error(`The identity provider refused the code exchange (${exchange.status}): ${await exchange.text()}`);
|
|
226
|
-
}
|
|
227
|
-
const tokens = await exchange.json();
|
|
228
|
-
const email = tokens.id_token ? emailFrom(tokens.id_token) : null;
|
|
229
|
-
|
|
230
|
-
saveSession(origin, {
|
|
231
|
-
access_token: tokens.access_token,
|
|
232
|
-
refresh_token: tokens.refresh_token,
|
|
233
|
-
expires_at: tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined,
|
|
234
|
-
email,
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
log(` ✓ Signed in${email ? ` as ${email}` : ""}\n`);
|
|
238
|
-
return { origin, accessToken: tokens.access_token, email };
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* A token for this universe, however it can be had, in the ruled order:
|
|
243
|
-
* UNOVERSE_TOKEN (CI) → live session (refreshing) → interactive login (TTY only).
|
|
244
|
-
*/
|
|
245
|
-
export async function tokenFor(origin, { interactive = true, log = console.log } = {}) {
|
|
246
|
-
if (process.env.UNOVERSE_TOKEN) return process.env.UNOVERSE_TOKEN;
|
|
247
|
-
|
|
248
|
-
const config = await discover(origin);
|
|
249
|
-
if (config.authEnabled && config.issuer && config.clientId) {
|
|
250
|
-
try {
|
|
251
|
-
const endpoints = await oidcEndpoints(config.issuer);
|
|
252
|
-
const live = await freshToken(origin, { tokenEndpoint: endpoints.token_endpoint, clientId: config.clientId });
|
|
253
|
-
if (live) return live;
|
|
254
|
-
} catch {
|
|
255
|
-
/* IdP unreachable: fall through to the interactive path, which explains itself */
|
|
256
|
-
}
|
|
257
|
-
} else if (!config.authEnabled) {
|
|
258
|
-
throw new Error(
|
|
259
|
-
`${origin} has authentication switched off.\n` +
|
|
260
|
-
` To deploy there, set UNOVERSE_TOKEN to a publish key minted on the universe itself.`,
|
|
261
|
-
);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (!interactive || !process.stdin.isTTY) {
|
|
265
|
-
throw new Error(
|
|
266
|
-
`No credential for ${origin}. In CI, set UNOVERSE_TOKEN to a publish key.\n` +
|
|
267
|
-
` At a terminal, run: unoverse login ${origin}`,
|
|
268
|
-
);
|
|
269
|
-
}
|
|
270
|
-
const { accessToken } = await login(origin, { log });
|
|
271
|
-
return accessToken;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
export { getSession };
|
package/lib/session.mjs
DELETED
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Per-machine sessions: ~/.unoverse/sessions.json, keyed by universe origin.
|
|
3
|
-
*
|
|
4
|
-
* THE REPO SAYS WHERE, THE MACHINE PROVES WHO. unoverse.yaml (committed) names the
|
|
5
|
-
* universe; this file (0600, home directory, never inside a project) holds the tokens
|
|
6
|
-
* that prove the developer to it. Same split as .git/config vs ~/.ssh. Nothing under a
|
|
7
|
-
* project folder ever holds a credential, so nothing can be committed or swept into a
|
|
8
|
-
* deploy by accident.
|
|
9
|
-
*
|
|
10
|
-
* A session is whatever the token endpoint returned: access_token, refresh_token when
|
|
11
|
-
* the IdP granted one, expiry, and the email shown in prompts. Refresh happens here so
|
|
12
|
-
* callers only ever ask one question: "a token for this universe, or null".
|
|
13
|
-
*/
|
|
14
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
|
15
|
-
import { homedir } from "node:os";
|
|
16
|
-
import { join } from "node:path";
|
|
17
|
-
|
|
18
|
-
const DIR = join(homedir(), ".unoverse");
|
|
19
|
-
const FILE = join(DIR, "sessions.json");
|
|
20
|
-
|
|
21
|
-
function load() {
|
|
22
|
-
if (!existsSync(FILE)) return {};
|
|
23
|
-
try {
|
|
24
|
-
const parsed = JSON.parse(readFileSync(FILE, "utf8"));
|
|
25
|
-
return parsed && typeof parsed === "object" ? parsed : {};
|
|
26
|
-
} catch {
|
|
27
|
-
return {}; // corrupt store: re-login beats a crash
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function save(all) {
|
|
32
|
-
mkdirSync(DIR, { recursive: true, mode: 0o700 });
|
|
33
|
-
writeFileSync(FILE, JSON.stringify(all, null, 2), { mode: 0o600 });
|
|
34
|
-
chmodSync(FILE, 0o600); // writeFileSync mode is ignored when the file already exists
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function getSession(origin) {
|
|
38
|
-
return load()[origin] ?? null;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Every universe origin this machine holds a session for. */
|
|
42
|
-
export function sessionOrigins() {
|
|
43
|
-
return Object.keys(load());
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function saveSession(origin, session) {
|
|
47
|
-
const all = load();
|
|
48
|
-
all[origin] = session;
|
|
49
|
-
save(all);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function clearSession(origin) {
|
|
53
|
-
const all = load();
|
|
54
|
-
delete all[origin];
|
|
55
|
-
save(all);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Seconds of slack so a token never expires mid-publish. */
|
|
59
|
-
const EXPIRY_SLACK_MS = 60_000;
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* A live access token for this universe, refreshing if the IdP granted a refresh token,
|
|
63
|
-
* or null when the developer has to log in again. `tokenEndpoint`/`clientId` come from
|
|
64
|
-
* the universe's own discovery (login.mjs) — nothing is hardcoded.
|
|
65
|
-
*/
|
|
66
|
-
export async function freshToken(origin, { tokenEndpoint, clientId } = {}) {
|
|
67
|
-
const session = getSession(origin);
|
|
68
|
-
if (!session?.access_token) return null;
|
|
69
|
-
if (session.expires_at && Date.now() < session.expires_at - EXPIRY_SLACK_MS) {
|
|
70
|
-
return session.access_token;
|
|
71
|
-
}
|
|
72
|
-
if (!session.refresh_token || !tokenEndpoint || !clientId) return null;
|
|
73
|
-
|
|
74
|
-
let response;
|
|
75
|
-
try {
|
|
76
|
-
response = await fetch(tokenEndpoint, {
|
|
77
|
-
method: "POST",
|
|
78
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
79
|
-
body: new URLSearchParams({
|
|
80
|
-
grant_type: "refresh_token",
|
|
81
|
-
client_id: clientId,
|
|
82
|
-
refresh_token: session.refresh_token,
|
|
83
|
-
}),
|
|
84
|
-
});
|
|
85
|
-
} catch {
|
|
86
|
-
return null; // offline: treat as expired, the caller decides what to say
|
|
87
|
-
}
|
|
88
|
-
if (!response.ok) {
|
|
89
|
-
clearSession(origin); // a refused refresh token is dead; keeping it re-fails forever
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
const body = await response.json();
|
|
93
|
-
saveSession(origin, {
|
|
94
|
-
...session,
|
|
95
|
-
access_token: body.access_token,
|
|
96
|
-
refresh_token: body.refresh_token ?? session.refresh_token,
|
|
97
|
-
expires_at: body.expires_in ? Date.now() + body.expires_in * 1000 : session.expires_at,
|
|
98
|
-
});
|
|
99
|
-
return body.access_token;
|
|
100
|
-
}
|