pico-engine 1.4.0 → 1.6.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 (82) hide show
  1. package/README.md +188 -0
  2. package/dist/RulesetRegistryLoaderFs.js +2 -0
  3. package/dist/auth/AuthService.js +601 -0
  4. package/dist/auth/index.js +8 -0
  5. package/dist/auth/webauthn.js +97 -0
  6. package/dist/bundledKrl.js +42 -0
  7. package/dist/cli.js +11 -0
  8. package/dist/identity/IdentityService.js +340 -0
  9. package/dist/identity/crossPico.js +238 -0
  10. package/dist/identity/dbHelpers.js +67 -0
  11. package/dist/identity/didcommIngressRoutes.js +44 -0
  12. package/dist/identity/didoModule.js +252 -0
  13. package/dist/identity/errors.js +11 -0
  14. package/dist/identity/establishSubscription.js +97 -0
  15. package/dist/identity/index.js +15 -0
  16. package/dist/identity/peerDid.js +9 -0
  17. package/dist/identity/skyIntro.js +194 -0
  18. package/dist/identity/skyProtocol.js +105 -0
  19. package/dist/identity/store.js +233 -0
  20. package/dist/identity/types.js +13 -0
  21. package/dist/identity/veramoDidComm.js +260 -0
  22. package/dist/identity/webvh.js +266 -0
  23. package/dist/identity/webvhCrypto.js +128 -0
  24. package/dist/identity/webvhRoutes.js +61 -0
  25. package/dist/index.js +100 -44
  26. package/dist/oauth/OAuthService.js +388 -0
  27. package/dist/oauth/acg.js +495 -0
  28. package/dist/oauth/channelEligibility.js +26 -0
  29. package/dist/oauth/errors.js +12 -0
  30. package/dist/oauth/index.js +21 -0
  31. package/dist/oauth/krlModule.js +27 -0
  32. package/dist/oauth/meshOAuth.js +43 -0
  33. package/dist/provisionRoot.js +118 -0
  34. package/dist/server.js +609 -15
  35. package/dist/uiChannelPolicies.js +48 -0
  36. package/krl/io.picolabs.did-o.krl +5 -1
  37. package/krl/io.picolabs.oauth.krl +48 -0
  38. package/krl/io.picolabs.pico-engine-ui.krl +106 -18
  39. package/krl/io.picolabs.subscription.krl +242 -23
  40. package/krl/io.picolabs.wrangler.krl +225 -16
  41. package/package.json +38 -9
  42. package/public/docs/krl/_sidebar.md +1 -0
  43. package/public/docs/krl/discovery.md +144 -0
  44. package/public/docs/krl/modules/ctx.md +8 -0
  45. package/public/docs/krl/modules/event.md +41 -0
  46. package/public/pico-engine-ui.css +1 -1
  47. package/public/pico-engine-ui.js +24 -20
  48. package/public/pico-labs-logo.png +0 -0
  49. package/src/RulesetRegistryLoaderFs.ts +2 -0
  50. package/src/auth/AuthService.ts +850 -0
  51. package/src/auth/index.ts +17 -0
  52. package/src/auth/webauthn.ts +182 -0
  53. package/src/bundledKrl.ts +42 -0
  54. package/src/cli.ts +11 -0
  55. package/src/identity/IdentityService.ts +571 -0
  56. package/src/identity/crossPico.ts +371 -0
  57. package/src/identity/dbHelpers.ts +51 -0
  58. package/src/identity/didcommIngressRoutes.ts +54 -0
  59. package/src/identity/didoModule.ts +388 -0
  60. package/src/identity/errors.ts +8 -0
  61. package/src/identity/establishSubscription.ts +160 -0
  62. package/src/identity/index.ts +24 -0
  63. package/src/identity/peerDid.ts +22 -0
  64. package/src/identity/skyIntro.ts +321 -0
  65. package/src/identity/skyProtocol.ts +192 -0
  66. package/src/identity/store.ts +343 -0
  67. package/src/identity/types.ts +63 -0
  68. package/src/identity/veramoDidComm.ts +363 -0
  69. package/src/identity/webvh.ts +325 -0
  70. package/src/identity/webvhCrypto.ts +200 -0
  71. package/src/identity/webvhRoutes.ts +64 -0
  72. package/src/index.ts +145 -53
  73. package/src/oauth/OAuthService.ts +510 -0
  74. package/src/oauth/acg.ts +666 -0
  75. package/src/oauth/channelEligibility.ts +26 -0
  76. package/src/oauth/errors.ts +10 -0
  77. package/src/oauth/index.ts +14 -0
  78. package/src/oauth/krlModule.ts +31 -0
  79. package/src/oauth/meshOAuth.ts +50 -0
  80. package/src/provisionRoot.ts +151 -0
  81. package/src/server.ts +700 -24
  82. package/src/uiChannelPolicies.ts +49 -0
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerWebvhRoutes = registerWebvhRoutes;
4
+ const webvh_1 = require("./webvh");
5
+ const errors_1 = require("./errors");
6
+ function registerWebvhRoutes(app, identity) {
7
+ app.get("/identity/resolve", async (req, res) => {
8
+ try {
9
+ const did = String(req.query.did || "").trim();
10
+ if (!did) {
11
+ res.status(400).json({ error: "Missing did query parameter" });
12
+ return;
13
+ }
14
+ const doc = await identity.resolveDid("", did);
15
+ res.json({ did, didDocument: doc });
16
+ }
17
+ catch (err) {
18
+ sendIdentityError(res, err);
19
+ }
20
+ });
21
+ app.get("/picos/:picoId/did.jsonl", async (req, res) => {
22
+ try {
23
+ const picoId = decodeURIComponent(req.params.picoId);
24
+ const jsonl = await identity.getWebvhLogJsonl(picoId);
25
+ if (!jsonl) {
26
+ res.status(404).send("Not found");
27
+ return;
28
+ }
29
+ const log = jsonl
30
+ .trim()
31
+ .split("\n")
32
+ .map((line) => JSON.parse(line));
33
+ await (0, webvh_1.resolveLocalWebvhLog)(log);
34
+ res.type("application/jsonld+json").send(jsonl);
35
+ }
36
+ catch (err) {
37
+ sendIdentityError(res, err);
38
+ }
39
+ });
40
+ app.get("/picos/:picoId/did.json", async (req, res) => {
41
+ try {
42
+ const picoId = decodeURIComponent(req.params.picoId);
43
+ const doc = await identity.getParallelWebDoc(picoId);
44
+ if (!doc) {
45
+ res.status(404).send("Not found");
46
+ return;
47
+ }
48
+ res.json(doc);
49
+ }
50
+ catch (err) {
51
+ sendIdentityError(res, err);
52
+ }
53
+ });
54
+ }
55
+ function sendIdentityError(res, err) {
56
+ if (err instanceof errors_1.IdentityError) {
57
+ res.status(err.statusCode).json({ error: err.message });
58
+ return;
59
+ }
60
+ res.status(500).json({ error: err.message || "Internal error" });
61
+ }
package/dist/index.js CHANGED
@@ -7,20 +7,32 @@ 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 identity_1 = require("./identity");
12
+ const oauth_1 = require("./oauth");
10
13
  const logging_1 = require("./logging");
14
+ const provisionRoot_1 = require("./provisionRoot");
11
15
  const RulesetRegistryLoaderFs_1 = require("./RulesetRegistryLoaderFs");
12
16
  const server_1 = require("./server");
13
- const toFileUrl_1 = require("./utils/toFileUrl");
14
17
  const charwise = require("charwise");
15
18
  const safeJsonCodec = require("level-json-coerce-null");
16
19
  const homeDir = require("home-dir");
17
20
  const version = require("../package.json").version;
18
21
  async function startEngine(configuration = {}) {
22
+ var _a, _b;
19
23
  let home = configuration.home;
20
24
  let port = configuration.port;
21
25
  let base_url = configuration.base_url;
22
26
  if (typeof home !== "string") {
23
- home = homeDir(".pico-engine");
27
+ const envHome = process.env.PICO_ENGINE_HOME;
28
+ if (typeof envHome === "string" &&
29
+ envHome.length > 0 &&
30
+ process.env.NODE_ENV === "test") {
31
+ home = envHome;
32
+ }
33
+ else {
34
+ home = homeDir(".pico-engine");
35
+ }
24
36
  }
25
37
  await makeDir(home);
26
38
  const logFilePath = path.resolve(home, "pico-engine.log");
@@ -36,47 +48,85 @@ async function startEngine(configuration = {}) {
36
48
  log,
37
49
  modules: configuration.modules,
38
50
  useEventInputTime: configuration.useEventInputTime,
51
+ autoCreateRootPico: (_a = configuration.autoCreateRootPico) !== null && _a !== void 0 ? _a : false,
39
52
  getPicoLogs(picoId) {
40
53
  return (0, logging_1.getPicoLogs)(logFilePath, picoId);
41
54
  },
42
55
  });
56
+ const pf = core.picoFramework;
57
+ const identity = new identity_1.IdentityStore({ db: pf.db });
58
+ let identityService;
59
+ identityService = new identity_1.IdentityService({
60
+ store: identity,
61
+ getBaseUrl: () => core.base_url || base_url || "",
62
+ pf,
63
+ });
64
+ core.onPicoCreated = async (picoId, ctx) => {
65
+ if (core.base_url) {
66
+ await identityService.ensureWebvhDid(picoId, { isRoot: ctx.isRoot });
67
+ }
68
+ };
69
+ core.modules["dido"] = (0, identity_1.initDidoModule)(identityService);
43
70
  await core.start();
44
71
  const rsRegistry = core.rsRegistry;
45
- const pf = core.picoFramework;
46
- const krl_urls = [
47
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.pico-engine-ui.krl")),
48
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.wrangler.krl")),
49
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.subscription.krl")),
50
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.did-o.krl")),
51
- (0, toFileUrl_1.toFileUrl)(path.resolve(__dirname, "..", "krl", "io.picolabs.pds.krl")),
52
- ];
53
- for (const url of krl_urls) {
54
- const { ruleset } = await rsRegistry.flush(url);
55
- await pf.rootPico.install(ruleset, { url, config: {} });
72
+ // Fresh engines boot with zero roots. Adopt + (re)provision only when roots
73
+ // already exist (test harness with autoCreateRootPico, or a migrated DB).
74
+ let uiECI = null;
75
+ const existingRoots = pf.rootPicos();
76
+ if (existingRoots.length > 0) {
77
+ const provisioned = await (0, provisionRoot_1.provisionRoot)(pf, core, { root: existingRoots[0] });
78
+ uiECI = provisioned.uiECI;
56
79
  }
57
- let uiChannel = pf.rootPico
58
- .toReadOnly()
59
- .channels.find((chann) => "engine,ui" === chann.tags.slice(0).sort().join(","));
60
- if (!uiChannel) {
61
- uiChannel = (await pf.rootPico.newChannel({
62
- tags: ["engine", "ui"],
63
- eventPolicy: {
64
- allow: [{ domain: "engine_ui", name: "setup" }],
65
- deny: [],
66
- },
67
- })).toReadOnly();
68
- }
69
- await pf.eventWait({
70
- eci: uiChannel.id,
71
- domain: "engine_ui",
72
- name: "setup",
73
- data: { attrs: {} },
74
- time: 0,
80
+ const auth = new auth_1.AuthService({
81
+ db: pf.db,
82
+ webauthn: configuration.webauthn || (0, auth_1.makeWebAuthnAdapter)(),
83
+ getBaseUrl: () => core.base_url,
84
+ rpID: configuration.rpID,
85
+ rpName: configuration.rpName,
86
+ origin: configuration.origin,
87
+ allowSelfSignup: (_b = configuration.allowSelfSignup) !== null && _b !== void 0 ? _b : false,
88
+ flushBootstrapUrl: async (url) => {
89
+ const flushed = await rsRegistry.flush(url);
90
+ return { rid: flushed.rid };
91
+ },
92
+ provisionRoot: async (opts) => {
93
+ const { root, uiECI } = await (0, provisionRoot_1.provisionRoot)(pf, core, opts);
94
+ if (core.base_url) {
95
+ await identityService.ensureWebvhDid(root.id, { isRoot: true });
96
+ }
97
+ return { rootPicoId: root.id, uiECI };
98
+ },
99
+ getUiECI: (rootPicoId) => (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId),
100
+ getPrimaryRootPicoId: () => {
101
+ try {
102
+ return pf.rootPico.id;
103
+ }
104
+ catch (_a) {
105
+ return null;
106
+ }
107
+ },
108
+ onAccountClaimed: async (rootPicoId, displayName) => {
109
+ const uiChannel = (0, provisionRoot_1.uiECIForRoot)(pf, rootPicoId);
110
+ if (!uiChannel || !displayName.trim()) {
111
+ return;
112
+ }
113
+ await pf.eventWait({
114
+ eci: uiChannel,
115
+ domain: "engine_ui",
116
+ name: "box",
117
+ data: { attrs: { name: displayName.trim() } },
118
+ time: 0,
119
+ });
120
+ },
75
121
  });
76
- const uiECI = uiChannel.id;
77
- const app = (0, server_1.server)(core, uiECI);
122
+ const oauth = new oauth_1.OAuthService({
123
+ db: pf.db,
124
+ pf,
125
+ });
126
+ core.modules["oauth"] = (0, oauth_1.initOAuthModule)(oauth);
127
+ const app = (0, server_1.server)(core, uiECI, auth, oauth, identityService);
78
128
  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
79
- port = 3000;
129
+ port = process.env.NODE_ENV === "test" ? 0 : 3000;
80
130
  }
81
131
  await new Promise((resolve) => {
82
132
  const listener = app.listen(port, () => {
@@ -94,17 +144,19 @@ async function startEngine(configuration = {}) {
94
144
  base_url = `http://localhost:${port}`;
95
145
  }
96
146
  core.base_url = base_url;
147
+ await identityService.ensureWebvhForAllLoadedPicos();
97
148
  log.info(`Listening at ${base_url}`);
98
- pf.event({
99
- eci: uiECI,
100
- domain: "engine",
101
- name: "started",
102
- data: { attrs: {} },
103
- time: 0, // TODO remove this typescript requirement
104
- }).catch((error) => {
105
- log.error("Error signaling engine:started event", { error });
106
- // TODO signal all errors engine:error
107
- });
149
+ if (uiECI) {
150
+ pf.event({
151
+ eci: uiECI,
152
+ domain: "engine",
153
+ name: "started",
154
+ data: { attrs: {} },
155
+ time: 0, // TODO remove this typescript requirement
156
+ }).catch((error) => {
157
+ log.error("Error signaling engine:started event", { error });
158
+ });
159
+ }
108
160
  return {
109
161
  version,
110
162
  home,
@@ -113,5 +165,9 @@ async function startEngine(configuration = {}) {
113
165
  pf,
114
166
  uiECI,
115
167
  rsRegistry,
168
+ auth,
169
+ oauth,
170
+ identity,
171
+ identityService,
116
172
  };
117
173
  }
@@ -0,0 +1,388 @@
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
+ try {
172
+ const channel = this.lookupChannelReadOnly(eci);
173
+ if (channel.tags.includes("didcomm") &&
174
+ channel.tags.includes("ingress")) {
175
+ return false;
176
+ }
177
+ }
178
+ catch (_e) {
179
+ // channel not found — fall through
180
+ }
181
+ if (await this.channelRequiresBearer(eci)) {
182
+ return true;
183
+ }
184
+ return this.meshRequiresOAuth(eci);
185
+ }
186
+ async validateBearerToken(token, channelEci) {
187
+ return this.validateSkyBearerToken(token, channelEci);
188
+ }
189
+ /** Mesh-wide OAuth token (authorization_code grant) → root pico id. */
190
+ async resolveMeshBearerToken(token) {
191
+ const trimmed = (token || "").trim();
192
+ if (!trimmed) {
193
+ return null;
194
+ }
195
+ const record = await this.getTokenRecord(trimmed);
196
+ if (!record) {
197
+ return null;
198
+ }
199
+ if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
200
+ await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
201
+ return null;
202
+ }
203
+ if ((record.grant || "client_credentials") !== "authorization_code") {
204
+ return null;
205
+ }
206
+ if (!record.rootPicoId) {
207
+ return null;
208
+ }
209
+ return { rootPicoId: record.rootPicoId, scope: record.scope };
210
+ }
211
+ async validateSkyBearerToken(token, channelEci) {
212
+ const trimmed = (token || "").trim();
213
+ if (!trimmed || !channelEci) {
214
+ return false;
215
+ }
216
+ const record = await this.getTokenRecord(trimmed);
217
+ if (!record) {
218
+ return false;
219
+ }
220
+ if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
221
+ await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
222
+ return false;
223
+ }
224
+ const grant = record.grant || "client_credentials";
225
+ if (grant === "authorization_code") {
226
+ return (0, meshOAuth_1.isChannelUnderRoot)(this.deps.pf, channelEci, record.rootPicoId);
227
+ }
228
+ return record.channelEci === channelEci;
229
+ }
230
+ listApps(rootPicoId) {
231
+ return acg.listApps(this.acgContext(), rootPicoId);
232
+ }
233
+ registerApp(rootPicoId, input) {
234
+ return acg.registerApp(this.acgContext(), rootPicoId, input);
235
+ }
236
+ revokeApp(rootPicoId, clientId) {
237
+ return acg.revokeApp(this.acgContext(), rootPicoId, clientId);
238
+ }
239
+ getAppForAuthorize(params) {
240
+ return acg.getAppForAuthorize(this.acgContext(), params);
241
+ }
242
+ approveAuthorization(session, params) {
243
+ return acg.approveAuthorization(this.acgContext(), session, params);
244
+ }
245
+ authorizationCodeGrant(input) {
246
+ return acg.authorizationCodeGrant(this.acgContext(), input);
247
+ }
248
+ refreshTokenGrant(input) {
249
+ return acg.refreshTokenGrant(this.acgContext(), input);
250
+ }
251
+ tokenGrant(body) {
252
+ const grant_type = String(body.grant_type || "client_credentials").trim();
253
+ if (grant_type === "authorization_code") {
254
+ return this.authorizationCodeGrant(body);
255
+ }
256
+ if (grant_type === "refresh_token") {
257
+ return this.refreshTokenGrant(body);
258
+ }
259
+ return this.clientCredentialsGrant(body);
260
+ }
261
+ acgContext() {
262
+ return {
263
+ db: this.deps.db,
264
+ pf: this.deps.pf,
265
+ tokenTtlMs: this.tokenTtlMs,
266
+ putAccessToken: async (record) => {
267
+ const tokenRecord = {
268
+ token: record.token,
269
+ grant: "authorization_code",
270
+ rootPicoId: record.rootPicoId,
271
+ appId: record.appId,
272
+ accountId: record.accountId,
273
+ scope: record.scope,
274
+ expiresAt: record.expiresAt,
275
+ createdAt: new Date().toISOString(),
276
+ };
277
+ await this.deps.db.put([OAUTH_TOKEN_PREFIX, record.token], tokenRecord);
278
+ },
279
+ };
280
+ }
281
+ async getTokenRecord(token) {
282
+ return dbGet(this.deps.db, [OAUTH_TOKEN_PREFIX, token]);
283
+ }
284
+ /** Channel owner or an ancestor pico in the admin tree may manage webhook OAuth. */
285
+ assertChannelManagedBy(eci, callerPicoId) {
286
+ const channel = this.lookupChannelReadOnly(eci);
287
+ let pico = this.deps.pf.lookupChannel(eci).pico;
288
+ while (true) {
289
+ if (pico.id === callerPicoId) {
290
+ return channel;
291
+ }
292
+ if (!pico.parent) {
293
+ break;
294
+ }
295
+ pico = this.deps.pf.getPico(pico.parent);
296
+ }
297
+ throw new errors_1.OAuthError("Channel is not in this pico's subtree", "invalid_request", 403);
298
+ }
299
+ assertEligibleChannel(eci) {
300
+ const channel = this.lookupChannelReadOnly(eci);
301
+ if (!(0, channelEligibility_1.isOAuthEligibleChannel)(channel)) {
302
+ throw new errors_1.OAuthError("Channel is not eligible for OAuth webhooks", "invalid_client", 403);
303
+ }
304
+ return channel;
305
+ }
306
+ rootPicoIdForChannel(channel) {
307
+ const owner = this.deps.pf.lookupChannel(channel.id).pico;
308
+ let pico = owner;
309
+ while (pico.parent) {
310
+ pico = this.deps.pf.getPico(pico.parent);
311
+ }
312
+ return pico.id;
313
+ }
314
+ async getChannelOAuth(eci) {
315
+ return dbGet(this.deps.db, [OAUTH_CHANNEL_PREFIX, eci]);
316
+ }
317
+ }
318
+ exports.OAuthService = OAuthService;
319
+ async function dbGet(db, key) {
320
+ try {
321
+ const value = await db.get(key);
322
+ return value === undefined ? null : value;
323
+ }
324
+ catch (err) {
325
+ if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
326
+ return null;
327
+ }
328
+ throw err;
329
+ }
330
+ }
331
+ async function dbList(db, prefix) {
332
+ var _a, e_1, _b, _c;
333
+ const out = [];
334
+ const iter = db.iterator({
335
+ gte: prefix,
336
+ lte: prefix.concat([undefined]),
337
+ });
338
+ try {
339
+ 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) {
340
+ _c = iter_1_1.value;
341
+ _d = false;
342
+ const [key, value] = _c;
343
+ out.push({ key, value });
344
+ }
345
+ }
346
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
347
+ finally {
348
+ try {
349
+ if (!_d && !_a && (_b = iter_1.return)) await _b.call(iter_1);
350
+ }
351
+ finally { if (e_1) throw e_1.error; }
352
+ }
353
+ return out;
354
+ }
355
+ function resolveTokenTtlMs(expires_in, defaultMs) {
356
+ if (expires_in === undefined || expires_in === null || expires_in === "") {
357
+ return defaultMs;
358
+ }
359
+ if (typeof expires_in === "string" && expires_in.trim().toLowerCase() === "never") {
360
+ return null;
361
+ }
362
+ const seconds = typeof expires_in === "string" ? Number.parseInt(expires_in, 10) : expires_in;
363
+ if (seconds === 0) {
364
+ return null;
365
+ }
366
+ if (!Number.isFinite(seconds) ||
367
+ seconds < exports.MIN_TOKEN_TTL_SEC ||
368
+ seconds > exports.MAX_TOKEN_TTL_SEC) {
369
+ 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);
370
+ }
371
+ return seconds * 1000;
372
+ }
373
+ function randomSecret() {
374
+ return crypto.randomBytes(32).toString("base64url");
375
+ }
376
+ function randomSalt() {
377
+ return crypto.randomBytes(16).toString("base64url");
378
+ }
379
+ function hashSecret(secret, salt) {
380
+ return crypto.createHash("sha256").update(salt + secret).digest("base64url");
381
+ }
382
+ function verifySecret(secret, salt, expected) {
383
+ const actual = hashSecret(secret, salt);
384
+ if (actual.length !== expected.length) {
385
+ return false;
386
+ }
387
+ return crypto.timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
388
+ }