@clagentic/console 1.10.0-beta.3 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/lib/build-sha.json +2 -2
  2. package/lib/build-update-offer.js +29 -0
  3. package/lib/daemon.js +5 -9
  4. package/lib/grant-keys.js +24 -137
  5. package/lib/identity/config.js +118 -0
  6. package/lib/identity/contract.js +61 -0
  7. package/lib/identity/delivery.js +224 -0
  8. package/lib/identity/holder.js +87 -0
  9. package/lib/identity/index.js +229 -0
  10. package/lib/identity/jose.js +13 -0
  11. package/lib/identity/origin.js +28 -0
  12. package/lib/identity/owner.js +30 -0
  13. package/lib/identity/providers/gatekeeper.js +91 -0
  14. package/lib/identity/providers/jwks-self.js +85 -0
  15. package/lib/identity/providers/module.js +98 -0
  16. package/lib/identity/providers/signing-key.js +118 -0
  17. package/lib/identity/record.js +23 -0
  18. package/lib/identity/unavailable.js +29 -0
  19. package/lib/project-notifications.js +2 -3
  20. package/lib/prompt-kinds/permission.js +0 -18
  21. package/lib/prompt-registry.js +5 -13
  22. package/lib/public/css/notifications-center.css +2 -8
  23. package/lib/public/css/rewind.css +0 -1
  24. package/lib/public/modules/app-notifications.js +4 -7
  25. package/lib/public/modules/build-notice-gate.js +73 -0
  26. package/lib/public/modules/diagnostics.js +43 -1
  27. package/lib/public/modules/prompt-banner.js +0 -12
  28. package/lib/public/modules/prompt-kinds/permission-choices.js +1 -6
  29. package/lib/public/modules/prompt-kinds/permission.js +0 -15
  30. package/lib/sdk-bridge.js +82 -3
  31. package/lib/sessions.js +7 -0
  32. package/lib/turn-initiator.js +29 -14
  33. package/lib/utils.js +4 -7
  34. package/lib/ws-schema.js +3 -3
  35. package/lib/yoke/adapters/claude-worker.js +5 -5
  36. package/lib/yoke/adapters/claude.js +5 -5
  37. package/package.json +3 -1
  38. package/scripts/vendor-identity-vectors.js +52 -0
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+
3
+ // The local delivery directory of the Identity Assertion contract (section 6):
4
+ //
5
+ // <dir>/ mode 0700, owned by the holder's user
6
+ // identity.jwt the assertion, one compact JWS, a regular file
7
+ // tmp/ scratch for the holder
8
+ //
9
+ // This module creates such a directory, writes the assertion into it, checks a
10
+ // directory a provider handed back before the console passes it on, and removes
11
+ // the directories it created itself when the session ends. It never follows a
12
+ // symlink and never removes, unlinks or traverses anything it did not create: a
13
+ // directory a provider made is the provider's, and ends through its release.
14
+ //
15
+ // The console delivers only to a session that runs as its own user (a session of
16
+ // another OS user never reaches this module: lib/identity/index.js answers it with
17
+ // owner_unsupported first). Every directory made here is therefore owned by the
18
+ // console user and nobody else can put anything in it, so it is removed whole.
19
+
20
+ var fs = require("fs");
21
+ var path = require("path");
22
+ var crypto = require("crypto");
23
+ var contract = require("./contract");
24
+
25
+ var NAME_PATTERN = /^cc-[0-9a-f]{32}$/;
26
+ var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
27
+ // A directory this old cannot hold a valid assertion any more (twelve hours of
28
+ // lifetime plus an hour of slack), so it is an orphan of a crashed process.
29
+ var STALE_MS = (contract.MAX_LIFETIME_SECONDS + 3600) * 1000;
30
+
31
+ var swept = new Set();
32
+
33
+ function deliveryError(code, message) {
34
+ var err = new Error(message);
35
+ err.identityCode = code;
36
+ return err;
37
+ }
38
+
39
+ function supported() {
40
+ return process.platform !== "win32" && typeof process.getuid === "function";
41
+ }
42
+
43
+ function ensureRoot(root) {
44
+ if (typeof root !== "string" || !path.isAbsolute(root)) {
45
+ throw deliveryError("spawn_root_invalid", "the identity spawn root is not an absolute path");
46
+ }
47
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
48
+ var st = fs.lstatSync(root);
49
+ if (st.isSymbolicLink() || !st.isDirectory()) {
50
+ throw deliveryError("spawn_root_invalid", "the identity spawn root is not a directory");
51
+ }
52
+ if (st.uid !== process.getuid()) {
53
+ throw deliveryError("spawn_root_invalid", "the identity spawn root is not owned by the console user");
54
+ }
55
+ if (st.mode & 0o022) {
56
+ throw deliveryError("spawn_root_invalid", "the identity spawn root is writable by group or other");
57
+ }
58
+ }
59
+
60
+ function sweepStale(root) {
61
+ if (swept.has(root)) return;
62
+ swept.add(root);
63
+ var names;
64
+ try { names = fs.readdirSync(root); } catch (e) { return; }
65
+ var cutoff = Date.now() - STALE_MS;
66
+ names.forEach(function (name) {
67
+ if (!contract.matches(NAME_PATTERN, name)) return;
68
+ var full = path.join(root, name);
69
+ try {
70
+ var st = fs.lstatSync(full);
71
+ if (st.isDirectory() && st.mtimeMs < cutoff) removeOwnDir(full);
72
+ } catch (e) {
73
+ // An orphan that cannot be removed now is tried again on the next start.
74
+ }
75
+ });
76
+ }
77
+
78
+ // Creates an empty delivery directory under root, owned by the console user.
79
+ function allocateDir(root) {
80
+ ensureRoot(root);
81
+ sweepStale(root);
82
+ var dir = path.join(root, "cc-" + crypto.randomBytes(16).toString("hex"));
83
+ try {
84
+ fs.mkdirSync(dir, { mode: 0o700 });
85
+ fs.chmodSync(dir, 0o700);
86
+ var tmp = path.join(dir, contract.IDENTITY_TMP_DIR);
87
+ fs.mkdirSync(tmp, { mode: 0o700 });
88
+ } catch (e) {
89
+ try { removeOwnDir(dir); } catch (cleanupError) {
90
+ // What cannot be removed now is an orphan the next start's sweep retries.
91
+ }
92
+ throw deliveryError("spawn_dir_failed", "the identity directory could not be created");
93
+ }
94
+ return dir;
95
+ }
96
+
97
+ // Writes the assertion as identity.jwt: into tmp first, then renamed over, so a
98
+ // reader never sees a partial file.
99
+ function writeAssertion(dir, token) {
100
+ if (typeof token !== "string" || Buffer.byteLength(token) > contract.MAX_FILE_BYTES) {
101
+ throw deliveryError("assertion_invalid", "the assertion is missing or larger than the contract allows");
102
+ }
103
+ var staging = path.join(dir, contract.IDENTITY_TMP_DIR, "w-" + crypto.randomBytes(8).toString("hex"));
104
+ fs.writeFileSync(staging, token, { flag: "wx", mode: 0o600 });
105
+ fs.renameSync(staging, path.join(dir, contract.IDENTITY_FILE));
106
+ }
107
+
108
+ // One segment of a compact JWS: unpadded base64url. Node's decoder is lenient
109
+ // (it skips characters it does not know), so the syntax is checked first.
110
+ function isBase64UrlSegment(segment) {
111
+ return contract.matches(BASE64URL_PATTERN, segment) && segment.length % 4 !== 1;
112
+ }
113
+
114
+ function decodeClaims(token) {
115
+ var parts = token.split(".");
116
+ if (parts.length !== 3 || !parts.every(isBase64UrlSegment)) return null;
117
+ try {
118
+ var claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
119
+ return claims && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
120
+ } catch (e) {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ // The delivery checks a consumer makes (contract section 6), plus the shape of
126
+ // the claims the console records. The console is not the verifier: it does not
127
+ // check the signature, it refuses only a directory or file no consumer could
128
+ // accept. Returns the claims, or throws an error carrying `identityCode`.
129
+ function inspect(dir, expectedUid) {
130
+ if (typeof dir !== "string" || !path.isAbsolute(dir)) {
131
+ throw deliveryError("delivery_invalid", "the provider's directory is not an absolute path");
132
+ }
133
+ var st;
134
+ try { st = fs.lstatSync(dir); } catch (e) {
135
+ throw deliveryError("delivery_invalid", "the provider's directory does not exist");
136
+ }
137
+ if (st.isSymbolicLink() || !st.isDirectory()) {
138
+ throw deliveryError("delivery_invalid", "the provider's directory is a link or not a directory");
139
+ }
140
+ if (st.uid !== expectedUid || (st.mode & 0o077) !== 0) {
141
+ throw deliveryError("delivery_invalid", "the provider's directory is not private to the session's user");
142
+ }
143
+ var fd;
144
+ try {
145
+ // O_NONBLOCK so a FIFO planted at this name fails the regular-file check below
146
+ // instead of blocking the open (and the daemon's event loop) until a writer appears.
147
+ fd = fs.openSync(
148
+ path.join(dir, contract.IDENTITY_FILE),
149
+ fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK
150
+ );
151
+ } catch (e) {
152
+ throw deliveryError("delivery_invalid", "the provider left no readable assertion file");
153
+ }
154
+ var content;
155
+ try {
156
+ if (!fs.fstatSync(fd).isFile()) {
157
+ throw deliveryError("delivery_invalid", "the assertion file is not a regular file within the size limit");
158
+ }
159
+ // The size is not trusted: the file's owner can enlarge it after any check,
160
+ // so at most one byte more than the limit is ever read, and one more is refused.
161
+ var buffer = Buffer.alloc(contract.MAX_FILE_BYTES + 1);
162
+ var filled = 0;
163
+ var n;
164
+ do {
165
+ n = fs.readSync(fd, buffer, filled, buffer.length - filled, null);
166
+ filled += n;
167
+ } while (n > 0 && filled < buffer.length);
168
+ if (filled > contract.MAX_FILE_BYTES) {
169
+ throw deliveryError("delivery_invalid", "the assertion file is not a regular file within the size limit");
170
+ }
171
+ content = buffer.toString("utf8", 0, filled);
172
+ } finally {
173
+ fs.closeSync(fd);
174
+ }
175
+ var claims = decodeClaims(content.replace(/\n$/, ""));
176
+ if (!claims) throw deliveryError("assertion_invalid", "the assertion is not a compact JWS with a JSON claim set");
177
+ if (claims.cia !== contract.CONTRACT_MAJOR) {
178
+ throw deliveryError("assertion_invalid", "the assertion is not of a contract version the console supports");
179
+ }
180
+ if (typeof claims.dir !== "string" || path.normalize(claims.dir) !== path.normalize(dir)) {
181
+ throw deliveryError("assertion_invalid", "the assertion is not bound to its delivery directory");
182
+ }
183
+ if (contract.GRADES.indexOf(claims.grade) === -1 || contract.ORIGINS.indexOf(claims.origin) === -1) {
184
+ throw deliveryError("assertion_invalid", "the assertion carries an unknown grade or origin");
185
+ }
186
+ if (!Number.isInteger(claims.exp) || claims.exp * 1000 <= Date.now()) {
187
+ throw deliveryError("assertion_invalid", "the assertion has already expired");
188
+ }
189
+ return claims;
190
+ }
191
+
192
+ // Removes a directory the console created under its own spawn root, whole. One
193
+ // that is not a plain directory owned by the console user is not the console's
194
+ // and is left alone.
195
+ function removeOwnDir(dir) {
196
+ var st = fs.lstatSync(dir);
197
+ if (st.isSymbolicLink() || !st.isDirectory() || st.uid !== process.getuid()) return false;
198
+ fs.rmSync(dir, { recursive: true, force: true });
199
+ return true;
200
+ }
201
+
202
+ // Removes a delivery directory the console created, at the end of a session, on its
203
+ // name and its owner. Anything else is not the console's and is never touched.
204
+ // Never throws.
205
+ function removeDelivery(dir, expectedUid) {
206
+ try {
207
+ if (typeof dir !== "string" || !path.isAbsolute(dir) || path.dirname(dir) === path.parse(dir).root) return false;
208
+ if (!contract.matches(NAME_PATTERN, path.basename(dir))) return false;
209
+ var st = fs.lstatSync(dir);
210
+ if (st.isSymbolicLink() || !st.isDirectory() || st.uid !== expectedUid) return false;
211
+ return removeOwnDir(dir);
212
+ } catch (e) {
213
+ return false;
214
+ }
215
+ }
216
+
217
+ module.exports = {
218
+ supported: supported,
219
+ allocateDir: allocateDir,
220
+ writeAssertion: writeAssertion,
221
+ inspect: inspect,
222
+ removeDelivery: removeDelivery,
223
+ decodeClaims: decodeClaims,
224
+ };
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ // The one owner of everything a single begin() call yields (lib/identity/index.js).
4
+ //
5
+ // A provider may create directories through the console (ctx.allocateDir), create
6
+ // its own, or answer late or never. Whatever it does, every way the call can end
7
+ // goes through this object, and the invariant is kept in one place:
8
+ //
9
+ // - A directory the console created is removed at once, whatever the provider
10
+ // does or does not answer. Nothing waits on a provider's promise.
11
+ // - A directory the provider created is the provider's: the console never
12
+ // removes, unlinks or traverses anything in it. It ends through the provider's
13
+ // release and otherwise the issuer's own reaper.
14
+ // - The provider's release is called at most once for the session it yielded,
15
+ // after the removal above, and is never awaited: it is advisory and bounded.
16
+ //
17
+ // States: open -> abandoned (the console stopped waiting: new directories are
18
+ // refused and the ones made are removed) -> ended (the session, if any, was
19
+ // settled). end() is settle-once; abandon() may precede it.
20
+
21
+ var delivery = require("./delivery");
22
+
23
+ var RELEASE_TIMEOUT_MS = 10000;
24
+
25
+ // options: { provider, spawnRoot, warn, releaseTimeoutMs }
26
+ function createHolder(options) {
27
+ var made = new Set();
28
+ var abandoned = false;
29
+ var ended = false;
30
+ var releaseTimeoutMs = options.releaseTimeoutMs > 0 ? options.releaseTimeoutMs : RELEASE_TIMEOUT_MS;
31
+
32
+ function allocateDir() {
33
+ if (abandoned || ended) throw new Error("the console no longer waits for this identity session");
34
+ var dir = delivery.allocateDir(options.spawnRoot);
35
+ made.add(dir);
36
+ return dir;
37
+ }
38
+
39
+ function removeMade() {
40
+ made.forEach(function (dir) { delivery.removeDelivery(dir, process.getuid()); });
41
+ }
42
+
43
+ // Asks the provider to end the session, without waiting for it. A release that
44
+ // throws, rejects or hangs only produces a warning.
45
+ function callRelease(session) {
46
+ if (typeof options.provider.release !== "function") return;
47
+ var timer;
48
+ var limit = new Promise(function (resolve) {
49
+ timer = setTimeout(function () {
50
+ options.warn("[identity] provider release did not finish in time");
51
+ resolve();
52
+ }, releaseTimeoutMs);
53
+ if (timer.unref) timer.unref();
54
+ });
55
+ var call = Promise.resolve().then(function () {
56
+ return options.provider.release({ provider: session.provider, dir: session.dir });
57
+ });
58
+ Promise.race([call, limit])
59
+ .catch(function (err) { options.warn("[identity] provider release failed: " + (err && err.message)); })
60
+ .then(function () { clearTimeout(timer); });
61
+ }
62
+
63
+ // The console stops waiting for the provider.
64
+ function abandon() {
65
+ abandoned = true;
66
+ removeMade();
67
+ }
68
+
69
+ // Ends the call: `session` is what the provider yielded, or null when it yielded
70
+ // nothing (it was unavailable, failed, or answered nothing usable).
71
+ function end(session) {
72
+ if (ended) return;
73
+ ended = true;
74
+ removeMade();
75
+ if (!session) return;
76
+ callRelease(session);
77
+ }
78
+
79
+ return {
80
+ allocateDir: allocateDir,
81
+ abandon: abandon,
82
+ end: end,
83
+ isAbandoned: function () { return abandoned; },
84
+ };
85
+ }
86
+
87
+ module.exports = { createHolder: createHolder };
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+
3
+ // The identity surface of the console (contract version 1.0.0).
4
+ //
5
+ // At the start of an agent session the console asks its configured provider for
6
+ // an Identity Assertion, delivers it to the session's process through a private
7
+ // directory named by CLAGENTIC_IDENTITY_DIR, and removes the directory when the
8
+ // session ends. With nothing configured (the default) none of this runs: no
9
+ // provider is created, no file is touched, nothing is logged, and the session's
10
+ // environment is exactly what it was without the surface.
11
+ //
12
+ // When a provider is configured and cannot supply an identity, the session still
13
+ // starts, without CLAGENTIC_IDENTITY_DIR, and the person is told. Nothing is
14
+ // fabricated and no inherited identity is passed on.
15
+ //
16
+ // Runtimes. Claude sessions are covered. A Codex session is not: one Codex
17
+ // server process serves many threads, and an environment variable belongs to a
18
+ // process, so a per-session assertion cannot be told apart from another thread's.
19
+ // A Codex session therefore runs as class 3 (no assertion) and its record says so.
20
+
21
+ var contract = require("./contract");
22
+ var config = require("./config");
23
+ var delivery = require("./delivery");
24
+ var holderModule = require("./holder");
25
+ var originMap = require("./origin");
26
+ var unavailableModule = require("./unavailable");
27
+ var gatekeeperProvider = require("./providers/gatekeeper");
28
+ var jwksSelfProvider = require("./providers/jwks-self");
29
+ var moduleProvider = require("./providers/module");
30
+
31
+ var unavailable = unavailableModule.unavailable;
32
+
33
+ var COVERED_RUNTIME = "claude-code";
34
+ var PROVIDER_TIMEOUT_MS = 15000;
35
+
36
+ // Runs the provider's call and resolves with exactly one of
37
+ // { value } it answered (an answer may itself be an unavailability)
38
+ // { error } it threw or rejected
39
+ // { timedOut } it did not answer within `ms`
40
+ // When the limit wins, onTimeout(pending) runs so the caller can cancel the
41
+ // provider and claim whatever it yields later.
42
+ function askProvider(call, ms, onTimeout) {
43
+ var pending = new Promise(function (resolve) { resolve(call()); });
44
+ return new Promise(function (resolve) {
45
+ var settled = false;
46
+ function settle(outcome) {
47
+ if (settled) return;
48
+ settled = true;
49
+ clearTimeout(timer);
50
+ resolve(outcome);
51
+ }
52
+ // The limit is decided before onTimeout runs: cancelling the provider can
53
+ // settle its own promise synchronously, and that must not outrank the timeout.
54
+ var timer = setTimeout(function () {
55
+ settle({ timedOut: true });
56
+ onTimeout(pending);
57
+ }, ms);
58
+ pending.then(function (value) { settle({ value: value }); }, function (error) { settle({ error: error || new Error("rejected") }); });
59
+ });
60
+ }
61
+
62
+ // What a provider yields when it supplies a session: a directory, and so a
63
+ // thing to settle. An unavailability is not one.
64
+ function isSession(value) {
65
+ return !!value && typeof value === "object" && !unavailableModule.isUnavailable(value) && typeof value.dir === "string";
66
+ }
67
+
68
+ function createProvider(cfg, warn) {
69
+ switch (cfg.provider) {
70
+ case contract.PROVIDERS.GATEKEEPER: return gatekeeperProvider.createGatekeeperProvider(cfg, { warn: warn });
71
+ case contract.PROVIDERS.JWKS_SELF: return jwksSelfProvider.createJwksSelfProvider(cfg);
72
+ default: return moduleProvider.createModuleProvider(cfg, { warn: warn });
73
+ }
74
+ }
75
+
76
+ function declaredLease(origin, result) {
77
+ return {
78
+ dir: null,
79
+ record: { provider: contract.PROVIDERS.DECLARED, grade: null, origin: origin, unavailable: result.code },
80
+ notice: result.quiet
81
+ ? null
82
+ : "Clagentic: Console could not obtain an identity for this session (" + result.reason + "). The session is running without one.",
83
+ release: function () {},
84
+ };
85
+ }
86
+
87
+ // options.getConfig() returns the `identity` block of the configuration (or
88
+ // undefined); it is read at every session start, so a change reaches the next one.
89
+ // options.providerTimeoutMs overrides how long a provider may take; it exists so a
90
+ // test can make a provider settle late, and nothing in the console sets it.
91
+ // options.releaseTimeoutMs bounds how long a provider's release is waited on for a
92
+ // warning; it exists for the same reason.
93
+ function createIdentity(options) {
94
+ var warn = options.warn || console.warn;
95
+ var providerTimeoutMs = options.providerTimeoutMs > 0 ? options.providerTimeoutMs : PROVIDER_TIMEOUT_MS;
96
+ var current = { key: null, cfg: null, provider: null };
97
+
98
+ function resolve() {
99
+ var raw = options.getConfig();
100
+ var key = raw === undefined || raw === null ? "" : JSON.stringify(raw);
101
+ if (current.key !== key || current.cfg === null) {
102
+ var cfg = config.resolveConfig(raw, options.configDir);
103
+ current = {
104
+ key: key,
105
+ cfg: cfg,
106
+ provider: cfg.provider === "none" || cfg.provider === "invalid" ? null : createProvider(cfg, warn),
107
+ };
108
+ }
109
+ return current;
110
+ }
111
+
112
+ function isEnabled() {
113
+ var raw = options.getConfig();
114
+ return raw !== undefined && raw !== null && resolve().cfg.provider !== "none";
115
+ }
116
+
117
+ // request: { definition, initiator, rt, owner }
118
+ // definition the persona agent's name, or null
119
+ // initiator the turn's initiator (lib/turn-initiator.js)
120
+ // rt the runtime id of the session
121
+ // owner { uid, gid } of the OS user the session runs as, or null; a uid
122
+ // other than the console's is answered owner_unsupported
123
+ // Returns null when no provider is configured, else a lease:
124
+ // { dir, record, notice, release }
125
+ async function begin(request) {
126
+ var state = resolve();
127
+ if (state.cfg.provider === "none") return null;
128
+ var origin = originMap.originForInitiator(request.initiator);
129
+ if (state.cfg.provider === "invalid") return declaredLease(origin, unavailable("config_invalid", state.cfg.reason));
130
+ if (request.rt !== COVERED_RUNTIME) {
131
+ return declaredLease(origin, unavailable("runtime_unsupported",
132
+ "this runtime shares one process between sessions", { quiet: true }));
133
+ }
134
+ if (!delivery.supported()) return declaredLease(origin, unavailable("platform_unsupported", "identity delivery is not supported on this platform"));
135
+
136
+ // The console delivers only to a session running as its own user: a directory
137
+ // for another uid would have to be handed over to it, which the console never
138
+ // does. Decided before any provider is asked, so every provider class gets the
139
+ // same answer and nothing is allocated. It shows the usual notice.
140
+ var owner = request.owner || null;
141
+ if (owner && owner.uid !== process.getuid()) {
142
+ return declaredLease(origin, unavailable("owner_unsupported",
143
+ "the console delivers an identity only to a session that runs as its own user"));
144
+ }
145
+ var holder = holderModule.createHolder({
146
+ provider: state.provider, spawnRoot: state.cfg.spawnRoot,
147
+ warn: warn, releaseTimeoutMs: options.releaseTimeoutMs,
148
+ });
149
+ var controller = new AbortController();
150
+ var ctx = {
151
+ owner: owner,
152
+ // Aborted when the console stops waiting; a provider should stop its work.
153
+ signal: controller.signal,
154
+ allocateDir: holder.allocateDir,
155
+ // The typed answer of a provider that cannot supply an identity.
156
+ unavailable: unavailable,
157
+ };
158
+
159
+ // Every way this call can end goes through `holder`, once (lib/identity/holder.js):
160
+ // provider unavailable or failed holder.end(null)
161
+ // console stops waiting (timeout) holder.abandon(); the provider's late answer
162
+ // or failure then goes through holder.end
163
+ // session refused by the checks holder.end(session)
164
+ // lease issued holder.end(session) on lease.release()
165
+ var answer = await askProvider(
166
+ function () { return state.provider.obtainSession(request.definition || null, origin, request.rt, ctx); },
167
+ providerTimeoutMs,
168
+ function (late) {
169
+ holder.abandon();
170
+ controller.abort();
171
+ // Whatever the provider yields after this point has no lease to carry it.
172
+ late.then(function (value) {
173
+ holder.end(isSession(value) ? value : null);
174
+ }, function (err) {
175
+ holder.end(null);
176
+ warn("[identity] the provider failed after the console stopped waiting: " + (err && err.message));
177
+ });
178
+ }
179
+ );
180
+ var result;
181
+ if (answer.timedOut) {
182
+ return declaredLease(origin, unavailable("provider_timeout", "the identity provider did not answer in time"));
183
+ } else if (answer.error) {
184
+ var err = answer.error;
185
+ warn("[identity] provider failed: " + (err && err.message));
186
+ result = unavailable((err && err.identityCode) || "provider_error", err && err.identityCode ? err.message : "the identity provider failed");
187
+ } else {
188
+ result = answer.value;
189
+ }
190
+ if (!isSession(result)) {
191
+ holder.end(null);
192
+ return declaredLease(origin, unavailableModule.isUnavailable(result)
193
+ ? result
194
+ : unavailable("provider_result_invalid", "the identity provider returned no session"));
195
+ }
196
+
197
+ var claims;
198
+ try {
199
+ if (result.assertion !== undefined) delivery.writeAssertion(result.dir, result.assertion);
200
+ claims = delivery.inspect(result.dir, process.getuid());
201
+ // Whatever a provider says, a turn the console did not know a person typed
202
+ // is never delivered as a human one.
203
+ if (claims.origin === "human" && origin !== "human") {
204
+ throw Object.assign(new Error("the assertion claims a human origin for a turn a person did not type"), { identityCode: "origin_mismatch" });
205
+ }
206
+ } catch (checkErr) {
207
+ holder.end(result);
208
+ warn("[identity] the provider's session was refused: " + (checkErr && checkErr.message));
209
+ return declaredLease(origin, unavailable((checkErr && checkErr.identityCode) || "delivery_invalid", "the identity provider returned a session the console could not accept"));
210
+ }
211
+
212
+ return {
213
+ dir: result.dir,
214
+ record: { provider: result.provider, grade: claims.grade, origin: claims.origin },
215
+ notice: null,
216
+ release: function () { holder.end(result); },
217
+ };
218
+ }
219
+
220
+ // A lease for a session that is to run without an identity for a reason the
221
+ // caller found before asking any provider.
222
+ function declared(initiator, code, reason) {
223
+ return declaredLease(originMap.originForInitiator(initiator), unavailable(code, reason));
224
+ }
225
+
226
+ return { isEnabled: isEnabled, begin: begin, declared: declared };
227
+ }
228
+
229
+ module.exports = { createIdentity: createIdentity };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+
3
+ // jose is an ES module. It is loaded on first use, so a console with no
4
+ // identity provider configured never loads it.
5
+
6
+ var loading = null;
7
+
8
+ function loadJose() {
9
+ if (!loading) loading = import("jose");
10
+ return loading;
11
+ }
12
+
13
+ module.exports = { loadJose: loadJose };
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ // Maps the console's per-turn initiator (lib/turn-initiator.js) to the
4
+ // contract's origin vocabulary.
5
+ //
6
+ // "human" is produced only for a turn the console knows a person typed. A turn
7
+ // whose entry point named no initiator is never read as typed: it maps to
8
+ // "trigger", so an absent signal cannot render an agent as the human.
9
+
10
+ var turnInitiator = require("../turn-initiator");
11
+
12
+ var INITIATORS = turnInitiator.INITIATORS;
13
+
14
+ function originForInitiator(initiator) {
15
+ switch (initiator) {
16
+ case INITIATORS.HUMAN:
17
+ return "human";
18
+ case INITIATORS.SCHEDULED:
19
+ case INITIATORS.SCHEDULED_NOW:
20
+ return "scheduled";
21
+ case INITIATORS.LOOP:
22
+ return "loop";
23
+ default:
24
+ return "trigger";
25
+ }
26
+ }
27
+
28
+ module.exports = { originForInitiator: originForInitiator };
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ // Who a session's delivery directory belongs to: the OS user the session runs as.
4
+
5
+ // Failures of the lookup itself, as lib/os-users.js raises them: a name that is
6
+ // not a user name, a `getent` that answered nothing usable or exited non-zero
7
+ // (no such user). Anything else is not an expected outcome of a lookup.
8
+ function isExpectedLookupError(err) {
9
+ if (!err) return false;
10
+ if (err.message === "Invalid Linux username" || /^Unexpected getent output/.test(err.message)) return true;
11
+ return typeof err.status === "number";
12
+ }
13
+
14
+ // lookup(linuxUser) returns { uid, gid } or throws. Returns { owner } where owner
15
+ // is { uid, gid }, or { unresolved: true } when the user cannot be told. An
16
+ // unexpected failure is logged through warn; the session still starts without an
17
+ // identity, as for an expected one.
18
+ function resolveOwner(linuxUser, lookup, warn) {
19
+ try {
20
+ var info = lookup(linuxUser);
21
+ if (Number.isInteger(info.uid) && Number.isInteger(info.gid)) return { owner: { uid: info.uid, gid: info.gid } };
22
+ } catch (err) {
23
+ if (!isExpectedLookupError(err)) {
24
+ warn("[identity] unexpected failure resolving the session's OS user: " + (err && err.message));
25
+ }
26
+ }
27
+ return { unresolved: true };
28
+ }
29
+
30
+ module.exports = { resolveOwner: resolveOwner, isExpectedLookupError: isExpectedLookupError };