pico-engine 1.3.0 → 1.5.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 (43) hide show
  1. package/README.md +147 -0
  2. package/dist/RulesetRegistryLoaderFs.js +4 -7
  3. package/dist/auth/AuthService.js +537 -0
  4. package/dist/auth/index.js +8 -0
  5. package/dist/auth/webauthn.js +97 -0
  6. package/dist/cli.js +11 -0
  7. package/dist/index.js +83 -46
  8. package/dist/logging.js +36 -27
  9. package/dist/oauth/OAuthService.js +356 -0
  10. package/dist/oauth/acg.js +495 -0
  11. package/dist/oauth/channelEligibility.js +26 -0
  12. package/dist/oauth/errors.js +12 -0
  13. package/dist/oauth/index.js +21 -0
  14. package/dist/oauth/krlModule.js +27 -0
  15. package/dist/oauth/meshOAuth.js +43 -0
  16. package/dist/provisionRoot.js +80 -0
  17. package/dist/server.js +565 -17
  18. package/dist/utils/toFileUrl.js +1 -2
  19. package/krl/io.picolabs.did-o.krl +25 -5
  20. package/krl/io.picolabs.oauth.krl +48 -0
  21. package/krl/io.picolabs.pds.krl +344 -0
  22. package/krl/io.picolabs.pico-engine-ui.krl +43 -10
  23. package/krl/io.picolabs.wrangler.krl +21 -20
  24. package/package.json +29 -29
  25. package/public/pico-engine-ui.css +4 -4
  26. package/public/pico-engine-ui.js +50 -16
  27. package/public/pico-labs-logo.png +0 -0
  28. package/src/RulesetRegistryLoaderFs.ts +6 -10
  29. package/src/auth/AuthService.ts +755 -0
  30. package/src/auth/index.ts +17 -0
  31. package/src/auth/webauthn.ts +182 -0
  32. package/src/cli.ts +11 -0
  33. package/src/index.ts +123 -56
  34. package/src/logging.ts +36 -47
  35. package/src/oauth/OAuthService.ts +474 -0
  36. package/src/oauth/acg.ts +666 -0
  37. package/src/oauth/channelEligibility.ts +26 -0
  38. package/src/oauth/errors.ts +10 -0
  39. package/src/oauth/index.ts +14 -0
  40. package/src/oauth/krlModule.ts +31 -0
  41. package/src/oauth/meshOAuth.ts +50 -0
  42. package/src/provisionRoot.ts +97 -0
  43. package/src/server.ts +647 -17
package/dist/index.js CHANGED
@@ -1,24 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startEngine = void 0;
3
+ exports.startEngine = startEngine;
4
4
  const krl_stdlib_1 = require("krl-stdlib");
5
- const leveldown_1 = require("leveldown");
5
+ const classic_level_1 = require("classic-level");
6
6
  const _ = require("lodash");
7
7
  const makeDir = require("make-dir");
8
8
  const path = require("path");
9
9
  const pico_engine_core_1 = require("pico-engine-core");
10
+ const auth_1 = require("./auth");
11
+ const oauth_1 = require("./oauth");
10
12
  const logging_1 = require("./logging");
13
+ const provisionRoot_1 = require("./provisionRoot");
11
14
  const RulesetRegistryLoaderFs_1 = require("./RulesetRegistryLoaderFs");
12
15
  const server_1 = require("./server");
13
- const toFileUrl_1 = require("./utils/toFileUrl");
16
+ const charwise = require("charwise");
17
+ const safeJsonCodec = require("level-json-coerce-null");
14
18
  const homeDir = require("home-dir");
15
19
  const version = require("../package.json").version;
16
20
  async function startEngine(configuration = {}) {
21
+ var _a, _b;
17
22
  let home = configuration.home;
18
23
  let port = configuration.port;
19
24
  let base_url = configuration.base_url;
20
25
  if (typeof home !== "string") {
21
- home = homeDir(".pico-engine");
26
+ const envHome = process.env.PICO_ENGINE_HOME;
27
+ if (typeof envHome === "string" &&
28
+ envHome.length > 0 &&
29
+ process.env.NODE_ENV === "test") {
30
+ home = envHome;
31
+ }
32
+ else {
33
+ home = homeDir(".pico-engine");
34
+ }
22
35
  }
23
36
  await makeDir(home);
24
37
  const logFilePath = path.resolve(home, "pico-engine.log");
@@ -26,11 +39,15 @@ async function startEngine(configuration = {}) {
26
39
  ? configuration.log
27
40
  : (0, krl_stdlib_1.makeKrlLogger)((0, logging_1.makeRotatingFileLogWriter)(logFilePath));
28
41
  const core = new pico_engine_core_1.PicoEngineCore({
29
- leveldown: (0, leveldown_1.default)(path.resolve(home, "db")),
42
+ db: new classic_level_1.ClassicLevel(path.resolve(home, "db"), {
43
+ keyEncoding: charwise,
44
+ valueEncoding: safeJsonCodec,
45
+ }),
30
46
  rsRegLoader: (0, RulesetRegistryLoaderFs_1.RulesetRegistryLoaderFs)(home),
31
47
  log,
32
48
  modules: configuration.modules,
33
49
  useEventInputTime: configuration.useEventInputTime,
50
+ autoCreateRootPico: (_a = configuration.autoCreateRootPico) !== null && _a !== void 0 ? _a : false,
34
51
  getPicoLogs(picoId) {
35
52
  return (0, logging_1.getPicoLogs)(logFilePath, picoId);
36
53
  },
@@ -38,39 +55,57 @@ async function startEngine(configuration = {}) {
38
55
  await core.start();
39
56
  const rsRegistry = core.rsRegistry;
40
57
  const pf = core.picoFramework;
41
- const krl_urls = [
42
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.pico-engine-ui.krl")),
43
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.wrangler.krl")),
44
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.subscription.krl")),
45
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.did-o.krl")),
46
- ];
47
- for (const url of krl_urls) {
48
- const { ruleset } = await rsRegistry.flush(url);
49
- await pf.rootPico.install(ruleset, { url, config: {} });
50
- }
51
- let uiChannel = pf.rootPico
52
- .toReadOnly()
53
- .channels.find((chann) => "engine,ui" === chann.tags.slice(0).sort().join(","));
54
- if (!uiChannel) {
55
- uiChannel = (await pf.rootPico.newChannel({
56
- tags: ["engine", "ui"],
57
- eventPolicy: {
58
- allow: [{ domain: "engine_ui", name: "setup" }],
59
- deny: [],
60
- },
61
- })).toReadOnly();
58
+ // Fresh engines boot with zero roots. Adopt + (re)provision only when roots
59
+ // already exist (test harness with autoCreateRootPico, or a migrated DB).
60
+ let uiECI = null;
61
+ const existingRoots = pf.rootPicos();
62
+ if (existingRoots.length > 0) {
63
+ const provisioned = await (0, provisionRoot_1.provisionRoot)(pf, core, { root: existingRoots[0] });
64
+ uiECI = provisioned.uiECI;
62
65
  }
63
- await pf.eventWait({
64
- eci: uiChannel.id,
65
- domain: "engine_ui",
66
- name: "setup",
67
- data: { attrs: {} },
68
- time: 0,
66
+ const auth = new auth_1.AuthService({
67
+ db: pf.db,
68
+ webauthn: configuration.webauthn || (0, auth_1.makeWebAuthnAdapter)(),
69
+ getBaseUrl: () => core.base_url,
70
+ rpID: configuration.rpID,
71
+ rpName: configuration.rpName,
72
+ origin: configuration.origin,
73
+ allowSelfSignup: (_b = configuration.allowSelfSignup) !== null && _b !== void 0 ? _b : false,
74
+ provisionRoot: async (opts) => {
75
+ const { root, uiECI } = await (0, provisionRoot_1.provisionRoot)(pf, core, opts);
76
+ return { rootPicoId: root.id, uiECI };
77
+ },
78
+ getUiECI: (rootPicoId) => (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId),
79
+ getPrimaryRootPicoId: () => {
80
+ try {
81
+ return pf.rootPico.id;
82
+ }
83
+ catch (_a) {
84
+ return null;
85
+ }
86
+ },
87
+ onAccountClaimed: async (rootPicoId, displayName) => {
88
+ const uiChannel = (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId);
89
+ if (!uiChannel || !displayName.trim()) {
90
+ return;
91
+ }
92
+ await pf.eventWait({
93
+ eci: uiChannel,
94
+ domain: "engine_ui",
95
+ name: "box",
96
+ data: { attrs: { name: displayName.trim() } },
97
+ time: 0,
98
+ });
99
+ },
100
+ });
101
+ const oauth = new oauth_1.OAuthService({
102
+ db: pf.db,
103
+ pf,
69
104
  });
70
- const uiECI = uiChannel.id;
71
- const app = (0, server_1.server)(core, uiECI);
105
+ core.modules["oauth"] = (0, oauth_1.initOAuthModule)(oauth);
106
+ const app = (0, server_1.server)(core, uiECI, auth, oauth);
72
107
  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
73
- port = 3000;
108
+ port = process.env.NODE_ENV === "test" ? 0 : 3000;
74
109
  }
75
110
  await new Promise((resolve) => {
76
111
  const listener = app.listen(port, () => {
@@ -89,16 +124,17 @@ async function startEngine(configuration = {}) {
89
124
  }
90
125
  core.base_url = base_url;
91
126
  log.info(`Listening at ${base_url}`);
92
- pf.event({
93
- eci: uiECI,
94
- domain: "engine",
95
- name: "started",
96
- data: { attrs: {} },
97
- time: 0, // TODO remove this typescript requirement
98
- }).catch((error) => {
99
- log.error("Error signaling engine:started event", { error });
100
- // TODO signal all errors engine:error
101
- });
127
+ if (uiECI) {
128
+ pf.event({
129
+ eci: uiECI,
130
+ domain: "engine",
131
+ name: "started",
132
+ data: { attrs: {} },
133
+ time: 0, // TODO remove this typescript requirement
134
+ }).catch((error) => {
135
+ log.error("Error signaling engine:started event", { error });
136
+ });
137
+ }
102
138
  return {
103
139
  version,
104
140
  home,
@@ -107,6 +143,7 @@ async function startEngine(configuration = {}) {
107
143
  pf,
108
144
  uiECI,
109
145
  rsRegistry,
146
+ auth,
147
+ oauth,
110
148
  };
111
149
  }
112
- exports.startEngine = startEngine;
package/dist/logging.js CHANGED
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
2
9
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPicoLogs = exports.makeRotatingFileLogWriter = void 0;
10
+ exports.makeRotatingFileLogWriter = makeRotatingFileLogWriter;
11
+ exports.getPicoLogs = getPicoLogs;
4
12
  const fs = require("fs");
13
+ const readline = require("readline");
5
14
  const krl_stdlib_1 = require("krl-stdlib");
6
15
  const path = require("path");
7
- const split = require("split");
8
- const through2 = require("through2");
9
16
  const rfs = require("rotating-file-stream");
10
17
  const logStreams = {};
11
18
  function getRotatingFileStream(filePath) {
@@ -17,7 +24,7 @@ function getRotatingFileStream(filePath) {
17
24
  return filename + "." + index;
18
25
  }, {
19
26
  path: path.dirname(filePath),
20
- size: "100M",
27
+ size: "100M", // rotate every 10 MegaBytes written
21
28
  maxFiles: 12,
22
29
  });
23
30
  }
@@ -34,17 +41,21 @@ function makeRotatingFileLogWriter(filePath) {
34
41
  }
35
42
  return write;
36
43
  }
37
- exports.makeRotatingFileLogWriter = makeRotatingFileLogWriter;
38
44
  async function getPicoLogs(filePath, picoId) {
39
- return new Promise((resolve, reject) => {
40
- const output = [];
41
- fs.createReadStream(filePath)
42
- .pipe(split())
43
- .pipe(through2((chunk, enc, next) => {
44
- const line = chunk.toString();
45
+ var _a, e_1, _b, _c;
46
+ const output = [];
47
+ const rl = readline.createInterface({
48
+ input: fs.createReadStream(filePath),
49
+ });
50
+ try {
51
+ for (var _d = true, rl_1 = __asyncValues(rl), rl_1_1; rl_1_1 = await rl_1.next(), _a = rl_1_1.done, !_a; _d = true) {
52
+ _c = rl_1_1.value;
53
+ _d = false;
54
+ const line = _c;
55
+ // Each line in the readline input will be successively available here as
56
+ // `line`.
45
57
  if (line.indexOf(picoId) < 0) {
46
- // not my pico
47
- return next();
58
+ continue; // not my pico
48
59
  }
49
60
  let entry;
50
61
  try {
@@ -52,25 +63,23 @@ async function getPicoLogs(filePath, picoId) {
52
63
  }
53
64
  catch (err) { }
54
65
  if (!entry || entry.picoId !== picoId) {
55
- // not my pico
56
- return next();
66
+ continue; // not my pico
57
67
  }
58
68
  const time = new Date(entry.time);
59
69
  if (Date.now() - time.getTime() > 1000 * 60 * 60 * 12) {
60
- // too old
61
- return next();
70
+ continue; // too old
62
71
  }
63
72
  const out = Object.assign(Object.assign({}, entry), { level: krl_stdlib_1.krlLogLevelCodeToHuman[entry.level] || `${entry.level}`, time: entry.time, txnId: entry.txnId });
64
73
  delete out.picoId;
65
74
  output.push(out);
66
- next();
67
- }))
68
- .on("finish", () => {
69
- resolve(output);
70
- })
71
- .on("error", (err) => {
72
- reject(err);
73
- });
74
- });
75
+ }
76
+ }
77
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
78
+ finally {
79
+ try {
80
+ if (!_d && !_a && (_b = rl_1.return)) await _b.call(rl_1);
81
+ }
82
+ finally { if (e_1) throw e_1.error; }
83
+ }
84
+ return output;
75
85
  }
76
- exports.getPicoLogs = getPicoLogs;
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.OAuthService = exports.renderConsentHtml = exports.parseApproveBody = exports.parseAuthorizeQuery = exports.DEFAULT_ACG_SCOPE = exports.OAuthError = exports.MAX_TOKEN_TTL_SEC = exports.MIN_TOKEN_TTL_SEC = void 0;
11
+ const crypto = require("crypto");
12
+ const acg = require("./acg");
13
+ const channelEligibility_1 = require("./channelEligibility");
14
+ const errors_1 = require("./errors");
15
+ const meshOAuth_1 = require("./meshOAuth");
16
+ const OAUTH_CHANNEL_PREFIX = "oauth-channel";
17
+ const OAUTH_TOKEN_PREFIX = "oauth-token";
18
+ const DEFAULT_TOKEN_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
19
+ exports.MIN_TOKEN_TTL_SEC = 5 * 60; // 5 minutes
20
+ exports.MAX_TOKEN_TTL_SEC = 90 * 24 * 60 * 60; // 90 days
21
+ var errors_2 = require("./errors");
22
+ Object.defineProperty(exports, "OAuthError", { enumerable: true, get: function () { return errors_2.OAuthError; } });
23
+ var acg_1 = require("./acg");
24
+ Object.defineProperty(exports, "DEFAULT_ACG_SCOPE", { enumerable: true, get: function () { return acg_1.DEFAULT_ACG_SCOPE; } });
25
+ Object.defineProperty(exports, "parseAuthorizeQuery", { enumerable: true, get: function () { return acg_1.parseAuthorizeQuery; } });
26
+ Object.defineProperty(exports, "parseApproveBody", { enumerable: true, get: function () { return acg_1.parseApproveBody; } });
27
+ Object.defineProperty(exports, "renderConsentHtml", { enumerable: true, get: function () { return acg_1.renderConsentHtml; } });
28
+ class OAuthService {
29
+ constructor(deps) {
30
+ this.deps = deps;
31
+ }
32
+ get tokenTtlMs() {
33
+ var _a;
34
+ return (_a = this.deps.tokenTtlMs) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_MS;
35
+ }
36
+ lookupChannelReadOnly(eci) {
37
+ return this.deps.pf.lookupChannel(eci).toReadOnly();
38
+ }
39
+ channelStatus(eci) {
40
+ let channel;
41
+ try {
42
+ channel = this.lookupChannelReadOnly(eci);
43
+ }
44
+ catch (_e) {
45
+ return { eligible: false, enabled: false, hasSecret: false, reason: "Channel not found" };
46
+ }
47
+ if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
48
+ return {
49
+ eligible: false,
50
+ enabled: false,
51
+ hasSecret: false,
52
+ reason: "Channel is not eligible for OAuth webhooks",
53
+ };
54
+ }
55
+ return {
56
+ eligible: true,
57
+ enabled: true,
58
+ clientId: eci,
59
+ hasSecret: false,
60
+ };
61
+ }
62
+ async channelRequiresBearer(eci) {
63
+ try {
64
+ return (0, channelEligibility_1.isOAuthEligibleChannel)(this.lookupChannelReadOnly(eci));
65
+ }
66
+ catch (_e) {
67
+ return false;
68
+ }
69
+ }
70
+ meshRequiresOAuth(eci) {
71
+ return (0, meshOAuth_1.meshRequiresOAuth)(this.deps.pf, eci);
72
+ }
73
+ /** @deprecated use channelRequiresBearer */
74
+ async channelOAuthEnabled(eci) {
75
+ return this.channelRequiresBearer(eci);
76
+ }
77
+ async channelStatusAsync(eci) {
78
+ let channel;
79
+ try {
80
+ channel = this.lookupChannelReadOnly(eci);
81
+ }
82
+ catch (_e) {
83
+ return { eligible: false, enabled: false, hasSecret: false, reason: "Channel not found" };
84
+ }
85
+ if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
86
+ return {
87
+ eligible: false,
88
+ enabled: false,
89
+ hasSecret: false,
90
+ reason: "Channel is not eligible for OAuth webhooks",
91
+ };
92
+ }
93
+ const stored = await this.getChannelOAuth(eci);
94
+ const hasSecret = !!stored;
95
+ return {
96
+ eligible: true,
97
+ enabled: true,
98
+ clientId: eci,
99
+ hasSecret,
100
+ createdAt: stored === null || stored === void 0 ? void 0 : stored.createdAt,
101
+ };
102
+ }
103
+ async createChannelSecret(eci) {
104
+ const channel = this.assertEligibleChannel(eci);
105
+ const rootPicoId = this.rootPicoIdForChannel(channel);
106
+ const client_secret = randomSecret();
107
+ const secretSalt = randomSalt();
108
+ const record = {
109
+ channelEci: eci,
110
+ rootPicoId,
111
+ secretSalt,
112
+ secretHash: hashSecret(client_secret, secretSalt),
113
+ createdAt: new Date().toISOString(),
114
+ };
115
+ await this.deps.db.put([OAUTH_CHANNEL_PREFIX, eci], record);
116
+ await this.revokeTokens(eci);
117
+ return { client_id: eci, client_secret };
118
+ }
119
+ async revokeChannelSecret(eci) {
120
+ this.assertEligibleChannel(eci);
121
+ await this.deps.db.del([OAUTH_CHANNEL_PREFIX, eci]);
122
+ await this.revokeTokens(eci);
123
+ }
124
+ async revokeTokens(eci) {
125
+ const rows = await dbList(this.deps.db, [OAUTH_TOKEN_PREFIX]);
126
+ for (const row of rows) {
127
+ if (row.value.channelEci === eci) {
128
+ await this.deps.db.del(row.key);
129
+ }
130
+ }
131
+ }
132
+ async clientCredentialsGrant(input) {
133
+ const client_id = (input.client_id || "").trim();
134
+ const client_secret = (input.client_secret || "").trim();
135
+ if (client_id.startsWith("app_")) {
136
+ throw new errors_1.OAuthError("OAuth apps require grant_type=authorization_code or refresh_token, not client_credentials", "invalid_client", 401);
137
+ }
138
+ if (!client_id || !client_secret) {
139
+ throw new errors_1.OAuthError("Missing client credentials", "invalid_client", 401);
140
+ }
141
+ const channel = this.assertEligibleChannel(client_id);
142
+ const stored = await this.getChannelOAuth(client_id);
143
+ if (!stored) {
144
+ throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
145
+ }
146
+ if (!verifySecret(client_secret, stored.secretSalt, stored.secretHash)) {
147
+ throw new errors_1.OAuthError("Invalid client", "invalid_client", 401);
148
+ }
149
+ const tokenTtlMs = resolveTokenTtlMs(input.expires_in, this.tokenTtlMs);
150
+ const token = acg.mintAccessToken();
151
+ const expiresAt = tokenTtlMs === null ? 0 : Date.now() + tokenTtlMs;
152
+ const tokenRecord = {
153
+ token,
154
+ grant: "client_credentials",
155
+ channelEci: client_id,
156
+ rootPicoId: stored.rootPicoId,
157
+ expiresAt,
158
+ createdAt: new Date().toISOString(),
159
+ };
160
+ await this.deps.db.put([OAUTH_TOKEN_PREFIX, token], tokenRecord);
161
+ const response = {
162
+ access_token: token,
163
+ token_type: "Bearer",
164
+ };
165
+ if (tokenTtlMs !== null) {
166
+ response.expires_in = Math.floor(tokenTtlMs / 1000);
167
+ }
168
+ return response;
169
+ }
170
+ async skyRequiresBearer(eci) {
171
+ if (await this.channelRequiresBearer(eci)) {
172
+ return true;
173
+ }
174
+ return this.meshRequiresOAuth(eci);
175
+ }
176
+ async validateBearerToken(token, channelEci) {
177
+ return this.validateSkyBearerToken(token, channelEci);
178
+ }
179
+ async validateSkyBearerToken(token, channelEci) {
180
+ const trimmed = (token || "").trim();
181
+ if (!trimmed || !channelEci) {
182
+ return false;
183
+ }
184
+ const record = await this.getTokenRecord(trimmed);
185
+ if (!record) {
186
+ return false;
187
+ }
188
+ if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
189
+ await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
190
+ return false;
191
+ }
192
+ const grant = record.grant || "client_credentials";
193
+ if (grant === "authorization_code") {
194
+ return (0, meshOAuth_1.isChannelUnderRoot)(this.deps.pf, channelEci, record.rootPicoId);
195
+ }
196
+ return record.channelEci === channelEci;
197
+ }
198
+ listApps(rootPicoId) {
199
+ return acg.listApps(this.acgContext(), rootPicoId);
200
+ }
201
+ registerApp(rootPicoId, input) {
202
+ return acg.registerApp(this.acgContext(), rootPicoId, input);
203
+ }
204
+ revokeApp(rootPicoId, clientId) {
205
+ return acg.revokeApp(this.acgContext(), rootPicoId, clientId);
206
+ }
207
+ getAppForAuthorize(params) {
208
+ return acg.getAppForAuthorize(this.acgContext(), params);
209
+ }
210
+ approveAuthorization(session, params) {
211
+ return acg.approveAuthorization(this.acgContext(), session, params);
212
+ }
213
+ authorizationCodeGrant(input) {
214
+ return acg.authorizationCodeGrant(this.acgContext(), input);
215
+ }
216
+ refreshTokenGrant(input) {
217
+ return acg.refreshTokenGrant(this.acgContext(), input);
218
+ }
219
+ tokenGrant(body) {
220
+ const grant_type = String(body.grant_type || "client_credentials").trim();
221
+ if (grant_type === "authorization_code") {
222
+ return this.authorizationCodeGrant(body);
223
+ }
224
+ if (grant_type === "refresh_token") {
225
+ return this.refreshTokenGrant(body);
226
+ }
227
+ return this.clientCredentialsGrant(body);
228
+ }
229
+ acgContext() {
230
+ return {
231
+ db: this.deps.db,
232
+ pf: this.deps.pf,
233
+ tokenTtlMs: this.tokenTtlMs,
234
+ putAccessToken: async (record) => {
235
+ const tokenRecord = {
236
+ token: record.token,
237
+ grant: "authorization_code",
238
+ rootPicoId: record.rootPicoId,
239
+ appId: record.appId,
240
+ accountId: record.accountId,
241
+ scope: record.scope,
242
+ expiresAt: record.expiresAt,
243
+ createdAt: new Date().toISOString(),
244
+ };
245
+ await this.deps.db.put([OAUTH_TOKEN_PREFIX, record.token], tokenRecord);
246
+ },
247
+ };
248
+ }
249
+ async getTokenRecord(token) {
250
+ return dbGet(this.deps.db, [OAUTH_TOKEN_PREFIX, token]);
251
+ }
252
+ /** Channel owner or an ancestor pico in the admin tree may manage webhook OAuth. */
253
+ assertChannelManagedBy(eci, callerPicoId) {
254
+ const channel = this.lookupChannelReadOnly(eci);
255
+ let pico = this.deps.pf.lookupChannel(eci).pico;
256
+ while (true) {
257
+ if (pico.id === callerPicoId) {
258
+ return channel;
259
+ }
260
+ if (!pico.parent) {
261
+ break;
262
+ }
263
+ pico = this.deps.pf.getPico(pico.parent);
264
+ }
265
+ throw new errors_1.OAuthError("Channel is not in this pico's subtree", "invalid_request", 403);
266
+ }
267
+ assertEligibleChannel(eci) {
268
+ const channel = this.lookupChannelReadOnly(eci);
269
+ if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
270
+ throw new errors_1.OAuthError("Channel is not eligible for OAuth webhooks", "invalid_client", 403);
271
+ }
272
+ return channel;
273
+ }
274
+ rootPicoIdForChannel(channel) {
275
+ const owner = this.deps.pf.lookupChannel(channel.id).pico;
276
+ let pico = owner;
277
+ while (pico.parent) {
278
+ pico = this.deps.pf.getPico(pico.parent);
279
+ }
280
+ return pico.id;
281
+ }
282
+ async getChannelOAuth(eci) {
283
+ return dbGet(this.deps.db, [OAUTH_CHANNEL_PREFIX, eci]);
284
+ }
285
+ }
286
+ exports.OAuthService = OAuthService;
287
+ async function dbGet(db, key) {
288
+ try {
289
+ const value = await db.get(key);
290
+ return value === undefined ? null : value;
291
+ }
292
+ catch (err) {
293
+ if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
294
+ return null;
295
+ }
296
+ throw err;
297
+ }
298
+ }
299
+ async function dbList(db, prefix) {
300
+ var _a, e_1, _b, _c;
301
+ const out = [];
302
+ const iter = db.iterator({
303
+ gte: prefix,
304
+ lte: prefix.concat([undefined]),
305
+ });
306
+ try {
307
+ for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = await iter_1.next(), _a = iter_1_1.done, !_a; _d = true) {
308
+ _c = iter_1_1.value;
309
+ _d = false;
310
+ const [key, value] = _c;
311
+ out.push({ key, value });
312
+ }
313
+ }
314
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
315
+ finally {
316
+ try {
317
+ if (!_d && !_a && (_b = iter_1.return)) await _b.call(iter_1);
318
+ }
319
+ finally { if (e_1) throw e_1.error; }
320
+ }
321
+ return out;
322
+ }
323
+ function resolveTokenTtlMs(expires_in, defaultMs) {
324
+ if (expires_in === undefined || expires_in === null || expires_in === "") {
325
+ return defaultMs;
326
+ }
327
+ if (typeof expires_in === "string" && expires_in.trim().toLowerCase() === "never") {
328
+ return null;
329
+ }
330
+ const seconds = typeof expires_in === "string" ? Number.parseInt(expires_in, 10) : expires_in;
331
+ if (seconds === 0) {
332
+ return null;
333
+ }
334
+ if (!Number.isFinite(seconds) ||
335
+ seconds < exports.MIN_TOKEN_TTL_SEC ||
336
+ seconds > exports.MAX_TOKEN_TTL_SEC) {
337
+ throw new errors_1.OAuthError(`expires_in must be 0 (never), or between ${exports.MIN_TOKEN_TTL_SEC} and ${exports.MAX_TOKEN_TTL_SEC} seconds`, "invalid_request", 400);
338
+ }
339
+ return seconds * 1000;
340
+ }
341
+ function randomSecret() {
342
+ return crypto.randomBytes(32).toString("base64url");
343
+ }
344
+ function randomSalt() {
345
+ return crypto.randomBytes(16).toString("base64url");
346
+ }
347
+ function hashSecret(secret, salt) {
348
+ return crypto.createHash("sha256").update(salt + secret).digest("base64url");
349
+ }
350
+ function verifySecret(secret, salt, expected) {
351
+ const actual = hashSecret(secret, salt);
352
+ if (actual.length !== expected.length) {
353
+ return false;
354
+ }
355
+ return crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
356
+ }