@agimon-ai/po-identity 0.0.2-alpha.9 → 0.0.2-alpha.90

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 CHANGED
@@ -7,10 +7,10 @@ owner membership and unique subject marker in one transaction.
7
7
 
8
8
  ## Composition
9
9
 
10
- Node's global plugin consumes only the server environment explicitly admitted by the CLI, once at
10
+ Node's host-scope plugin consumes only the server environment explicitly admitted by the CLI, once at
11
11
  composition. It injects `po/sqlite` and `po/fs`. It does not use a session's `po/config`: that would let
12
12
  one session configure an issuer shared by every session. This was the coordinator-approved phase-1
13
- configuration decision. Configuration changes require restart. A future global config service can
13
+ configuration decision. Configuration changes require restart. A future host config service can
14
14
  provide hot reload. The Worker uses the same `identityConfiguration(env)` function.
15
15
 
16
16
  Required environment keys, with no defaults:
@@ -35,7 +35,7 @@ checked-in values. Hosts must serve the issuer through trusted HTTPS in producti
35
35
 
36
36
  ## Issuer endpoints
37
37
 
38
- All paths are under `/api/auth/`. Node mounts them only when the global identity API is composed.
38
+ All paths are under `/api/auth/`. Node mounts them only when the host-scope identity API is composed.
39
39
  The Worker branches to the identity object before its legacy attach-token gate. Other routes keep
40
40
  their existing authorization. Better Auth's session-only `/token` and built-in deletion endpoints
41
41
  are disabled: they must not bypass device binding or the deletion outbox.
@@ -63,7 +63,7 @@ const proof = {
63
63
  };
64
64
  const post = (path, description, schema, authentication) => ({
65
65
  id: `identity:${path}`,
66
- scope: "global",
66
+ scope: "host",
67
67
  path: `/api/auth/${path}`,
68
68
  method: "POST",
69
69
  description,
@@ -92,7 +92,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
92
92
  http: [
93
93
  {
94
94
  id: "identity:providers",
95
- scope: "global",
95
+ scope: "host",
96
96
  path: "/api/auth/providers",
97
97
  method: "GET",
98
98
  description: "Configured sign-in provider names only",
@@ -105,7 +105,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
105
105
  },
106
106
  ...["jwks", "revocations"].map((path) => ({
107
107
  id: `identity:${path}`,
108
- scope: "global",
108
+ scope: "host",
109
109
  path: `/api/auth/${path}`,
110
110
  method: "GET",
111
111
  description: path === "jwks" ? "Issuer public signing keys" : "Cursor-based issuer revocations without addresses",
@@ -147,7 +147,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
147
147
  post("devices/enroll", "Enroll with an account session and new-key enroll proof; later devices require C10 approval or trusted-hub attestation", proof, "owner"),
148
148
  {
149
149
  id: "identity:devices",
150
- scope: "global",
150
+ scope: "host",
151
151
  path: "/api/auth/devices",
152
152
  method: "GET",
153
153
  description: "List same-person devices, without keys or routing metadata",
@@ -173,7 +173,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
173
173
  }, "device"),
174
174
  {
175
175
  id: "identity:devices/approval:lookup",
176
- scope: "global",
176
+ scope: "host",
177
177
  path: "/api/auth/devices/approval",
178
178
  method: "GET",
179
179
  description: "Same-person approval challenge lookup and polling",
@@ -156,7 +156,7 @@ export declare const apiContracts: {
156
156
  schemas?: Record<string, boolean | object> | undefined;
157
157
  http: {
158
158
  id: string;
159
- scope: "global" | "session" | "workspace";
159
+ scope: "host" | "session" | "workspace";
160
160
  basePath?: string | undefined;
161
161
  path: string;
162
162
  method: "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
@@ -184,7 +184,7 @@ export declare const apiContracts: {
184
184
  }[];
185
185
  sockets: {
186
186
  id: string;
187
- scope: "global" | "session" | "workspace";
187
+ scope: "host" | "session" | "workspace";
188
188
  description: string;
189
189
  availability?: string | undefined;
190
190
  service: string;
@@ -59,7 +59,7 @@ const proof = {
59
59
  };
60
60
  const post = (path, description, schema, authentication) => ({
61
61
  id: `identity:${path}`,
62
- scope: "global",
62
+ scope: "host",
63
63
  path: `/api/auth/${path}`,
64
64
  method: "POST",
65
65
  description,
@@ -88,7 +88,7 @@ const apiContracts = defineApiContract({
88
88
  http: [
89
89
  {
90
90
  id: "identity:providers",
91
- scope: "global",
91
+ scope: "host",
92
92
  path: "/api/auth/providers",
93
93
  method: "GET",
94
94
  description: "Configured sign-in provider names only",
@@ -101,7 +101,7 @@ const apiContracts = defineApiContract({
101
101
  },
102
102
  ...["jwks", "revocations"].map((path) => ({
103
103
  id: `identity:${path}`,
104
- scope: "global",
104
+ scope: "host",
105
105
  path: `/api/auth/${path}`,
106
106
  method: "GET",
107
107
  description: path === "jwks" ? "Issuer public signing keys" : "Cursor-based issuer revocations without addresses",
@@ -143,7 +143,7 @@ const apiContracts = defineApiContract({
143
143
  post("devices/enroll", "Enroll with an account session and new-key enroll proof; later devices require C10 approval or trusted-hub attestation", proof, "owner"),
144
144
  {
145
145
  id: "identity:devices",
146
- scope: "global",
146
+ scope: "host",
147
147
  path: "/api/auth/devices",
148
148
  method: "GET",
149
149
  description: "List same-person devices, without keys or routing metadata",
@@ -169,7 +169,7 @@ const apiContracts = defineApiContract({
169
169
  }, "device"),
170
170
  {
171
171
  id: "identity:devices/approval:lookup",
172
- scope: "global",
172
+ scope: "host",
173
173
  path: "/api/auth/devices/approval",
174
174
  method: "GET",
175
175
  description: "Same-person approval challenge lookup and polling",
@@ -13,7 +13,7 @@ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
13
13
  /** Only selected global compositions install an issuer. Pairing-only hosts keep the attach gate. */
14
14
  const serverPlugin = (0, require("@agimon-ai/po-core/serverPlugin").defineServerPlugin)({
15
15
  name: "@agimon-ai/po-identity",
16
- global: async (plugin) => {
16
+ host: async (plugin) => {
17
17
  const environment = plugin.host.context.environment;
18
18
  if (!environment) throw new Error("Identity home requires an admitted server environment");
19
19
  const configuration = require_index$1.identityConfiguration(environment);
@@ -8,7 +8,7 @@ import { defineServerPlugin } from "@agimon-ai/po-core/serverPlugin";
8
8
  /** Only selected global compositions install an issuer. Pairing-only hosts keep the attach gate. */
9
9
  const serverPlugin = defineServerPlugin({
10
10
  name: "@agimon-ai/po-identity",
11
- global: async (plugin) => {
11
+ host: async (plugin) => {
12
12
  const environment = plugin.host.context.environment;
13
13
  if (!environment) throw new Error("Identity home requires an admitted server environment");
14
14
  const configuration = identityConfiguration(environment);
@@ -0,0 +1,110 @@
1
+ //#region src/services/identityHome/globalTier.ts
2
+ var GlobalTierRefusal = class extends Error {
3
+ status;
4
+ constructor(status, message) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ };
9
+ /** Largest stored global settings document, in UTF-8 bytes. The HTTP body cap is the same. */
10
+ const MEMBER_SETTINGS_MAX_BYTES = 16384;
11
+ async function settingsHash(yaml) {
12
+ return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(yaml))).toString("base64url");
13
+ }
14
+ /**
15
+ * Issuer-held global tier: per-membership settings and host visibility. Visibility lives beside the
16
+ * signed C6 host entries and never changes their bytes; it only filters what discovery returns.
17
+ */
18
+ function createGlobalTier(database, now, membership) {
19
+ async function readMemberSettings(subject, org) {
20
+ return database.transaction(async (tx) => {
21
+ await membership(tx, subject, org);
22
+ return await tx.get("SELECT yaml, hash, updatedAt FROM member_settings WHERE org = ? AND subject = ?", org, subject) ?? {
23
+ yaml: "",
24
+ hash: await settingsHash(""),
25
+ updatedAt: null
26
+ };
27
+ });
28
+ }
29
+ async function writeMemberSettings(subject, org, yaml, expectedHash) {
30
+ if (new TextEncoder().encode(yaml).byteLength > 16384) throw new GlobalTierRefusal(413, "Settings too large");
31
+ const hash = await settingsHash(yaml);
32
+ const empty = await settingsHash("");
33
+ return database.transaction(async (tx) => {
34
+ await membership(tx, subject, org);
35
+ if (((await tx.get("SELECT hash FROM member_settings WHERE org = ? AND subject = ?", org, subject))?.hash ?? empty) !== expectedHash) throw new GlobalTierRefusal(409, "Settings changed");
36
+ const updatedAt = now();
37
+ await tx.run("INSERT INTO member_settings (org, subject, yaml, hash, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, subject) DO UPDATE SET yaml = excluded.yaml, hash = excluded.hash, updatedAt = excluded.updatedAt", org, subject, yaml, hash, updatedAt);
38
+ return {
39
+ hash,
40
+ updatedAt
41
+ };
42
+ });
43
+ }
44
+ /** Org-visible hosts plus the caller's own. Hidden hosts are absent, so their endpoints never leave. */
45
+ async function visibleHosts(subject, org) {
46
+ return database.transaction(async (tx) => {
47
+ await membership(tx, subject, org);
48
+ return {
49
+ networkId: org,
50
+ hosts: (await tx.all(`SELECT h.entry, h.subject, COALESCE(v.visibility, 'org') AS visibility
51
+ FROM identity_roster_host h
52
+ JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject
53
+ LEFT JOIN host_visibility v ON v.org = h.networkId AND v.hostId = h.hostId
54
+ WHERE h.networkId = ? AND h.evicted = 0 AND (COALESCE(v.visibility, 'org') = 'org' OR h.subject = ?)
55
+ ORDER BY h.hostId`, org, subject)).map((row) => ({
56
+ entry: JSON.parse(row.entry),
57
+ visibility: row.visibility,
58
+ owned: row.subject === subject
59
+ }))
60
+ };
61
+ });
62
+ }
63
+ /**
64
+ * Member-facing roster reads omit hosts another member keeps private, and the voter and term changes
65
+ * that name them. Evictions stay: clients purge a paired host only on an explicit eviction record.
66
+ * Host-proof and voter reads keep the full issuer-signed snapshot.
67
+ */
68
+ async function memberRosterView(subject, org, snapshot) {
69
+ const hidden = new Set((await database.all("SELECT v.hostId FROM host_visibility v JOIN identity_roster_host h ON h.networkId = v.org AND h.hostId = v.hostId WHERE v.org = ? AND v.visibility = 'member' AND h.subject != ?", org, subject)).map((row) => row.hostId));
70
+ const { payload } = snapshot;
71
+ return {
72
+ tag: snapshot.tag,
73
+ payload: {
74
+ ...payload,
75
+ hosts: payload.hosts.filter((entry) => !hidden.has(entry.payload.hostId)),
76
+ changes: payload.changes.filter((entry) => entry.payload.change.kind === "evict" || !hidden.has(entry.payload.hostId))
77
+ }
78
+ };
79
+ }
80
+ /** `org` needs an owner or admin. The host's owner, or an owner or admin, may set `member`. */
81
+ async function setHostVisibility(subject, org, hostId, visibility) {
82
+ if (visibility !== "org" && visibility !== "member") throw new GlobalTierRefusal(400, "Invalid visibility");
83
+ return database.transaction(async (tx) => {
84
+ const role = await membership(tx, subject, org);
85
+ const host = await tx.get("SELECT h.subject FROM identity_roster_host h JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject WHERE h.networkId = ? AND h.hostId = ? AND h.evicted = 0", org, hostId);
86
+ const manager = role === "owner" || role === "admin";
87
+ if (!host || !manager && host.subject !== subject) throw new GlobalTierRefusal(404, "Host unavailable");
88
+ if (visibility === "org" && !manager) throw new GlobalTierRefusal(403, "Owner or admin required");
89
+ const updatedAt = now();
90
+ await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, hostId) DO UPDATE SET visibility = excluded.visibility, setBy = excluded.setBy, updatedAt = excluded.updatedAt", org, hostId, visibility, subject, updatedAt);
91
+ return {
92
+ hostId,
93
+ visibility,
94
+ setBy: subject,
95
+ updatedAt
96
+ };
97
+ });
98
+ }
99
+ return {
100
+ readMemberSettings,
101
+ writeMemberSettings,
102
+ visibleHosts,
103
+ memberRosterView,
104
+ setHostVisibility
105
+ };
106
+ }
107
+ //#endregion
108
+ exports.GlobalTierRefusal = GlobalTierRefusal;
109
+ exports.MEMBER_SETTINGS_MAX_BYTES = MEMBER_SETTINGS_MAX_BYTES;
110
+ exports.createGlobalTier = createGlobalTier;
@@ -0,0 +1,13 @@
1
+ import { FederationRoster } from "@agimon-ai/po-core";
2
+ import { SignedFederationEnvelope } from "@agimon-ai/po-web-security";
3
+ import { SqliteDatabase, SqliteExecutor } from "@earendil-works/pi-durable/storage/sqlite";
4
+ //#region src/services/identityHome/globalTier.d.ts
5
+ type SignedRoster = SignedFederationEnvelope<FederationRoster, 'po/roster/v1'>;
6
+ /**
7
+ * Roster as a member reads it: another member's private hosts are removed, so the issuer's whole-list
8
+ * signature is dropped. Host entries keep their own signed bytes. Without the issuer signature this
9
+ * view can never be applied as C6 state, so a member cannot replay it to make a host drop entries.
10
+ */
11
+ export type MemberRosterView = Pick<SignedRoster, 'tag' | 'payload'>;
12
+ //#endregion
13
+ export {};
@@ -0,0 +1,108 @@
1
+ //#region src/services/identityHome/globalTier.ts
2
+ var GlobalTierRefusal = class extends Error {
3
+ status;
4
+ constructor(status, message) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ };
9
+ /** Largest stored global settings document, in UTF-8 bytes. The HTTP body cap is the same. */
10
+ const MEMBER_SETTINGS_MAX_BYTES = 16384;
11
+ async function settingsHash(yaml) {
12
+ return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(yaml))).toString("base64url");
13
+ }
14
+ /**
15
+ * Issuer-held global tier: per-membership settings and host visibility. Visibility lives beside the
16
+ * signed C6 host entries and never changes their bytes; it only filters what discovery returns.
17
+ */
18
+ function createGlobalTier(database, now, membership) {
19
+ async function readMemberSettings(subject, org) {
20
+ return database.transaction(async (tx) => {
21
+ await membership(tx, subject, org);
22
+ return await tx.get("SELECT yaml, hash, updatedAt FROM member_settings WHERE org = ? AND subject = ?", org, subject) ?? {
23
+ yaml: "",
24
+ hash: await settingsHash(""),
25
+ updatedAt: null
26
+ };
27
+ });
28
+ }
29
+ async function writeMemberSettings(subject, org, yaml, expectedHash) {
30
+ if (new TextEncoder().encode(yaml).byteLength > 16384) throw new GlobalTierRefusal(413, "Settings too large");
31
+ const hash = await settingsHash(yaml);
32
+ const empty = await settingsHash("");
33
+ return database.transaction(async (tx) => {
34
+ await membership(tx, subject, org);
35
+ if (((await tx.get("SELECT hash FROM member_settings WHERE org = ? AND subject = ?", org, subject))?.hash ?? empty) !== expectedHash) throw new GlobalTierRefusal(409, "Settings changed");
36
+ const updatedAt = now();
37
+ await tx.run("INSERT INTO member_settings (org, subject, yaml, hash, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, subject) DO UPDATE SET yaml = excluded.yaml, hash = excluded.hash, updatedAt = excluded.updatedAt", org, subject, yaml, hash, updatedAt);
38
+ return {
39
+ hash,
40
+ updatedAt
41
+ };
42
+ });
43
+ }
44
+ /** Org-visible hosts plus the caller's own. Hidden hosts are absent, so their endpoints never leave. */
45
+ async function visibleHosts(subject, org) {
46
+ return database.transaction(async (tx) => {
47
+ await membership(tx, subject, org);
48
+ return {
49
+ networkId: org,
50
+ hosts: (await tx.all(`SELECT h.entry, h.subject, COALESCE(v.visibility, 'org') AS visibility
51
+ FROM identity_roster_host h
52
+ JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject
53
+ LEFT JOIN host_visibility v ON v.org = h.networkId AND v.hostId = h.hostId
54
+ WHERE h.networkId = ? AND h.evicted = 0 AND (COALESCE(v.visibility, 'org') = 'org' OR h.subject = ?)
55
+ ORDER BY h.hostId`, org, subject)).map((row) => ({
56
+ entry: JSON.parse(row.entry),
57
+ visibility: row.visibility,
58
+ owned: row.subject === subject
59
+ }))
60
+ };
61
+ });
62
+ }
63
+ /**
64
+ * Member-facing roster reads omit hosts another member keeps private, and the voter and term changes
65
+ * that name them. Evictions stay: clients purge a paired host only on an explicit eviction record.
66
+ * Host-proof and voter reads keep the full issuer-signed snapshot.
67
+ */
68
+ async function memberRosterView(subject, org, snapshot) {
69
+ const hidden = new Set((await database.all("SELECT v.hostId FROM host_visibility v JOIN identity_roster_host h ON h.networkId = v.org AND h.hostId = v.hostId WHERE v.org = ? AND v.visibility = 'member' AND h.subject != ?", org, subject)).map((row) => row.hostId));
70
+ const { payload } = snapshot;
71
+ return {
72
+ tag: snapshot.tag,
73
+ payload: {
74
+ ...payload,
75
+ hosts: payload.hosts.filter((entry) => !hidden.has(entry.payload.hostId)),
76
+ changes: payload.changes.filter((entry) => entry.payload.change.kind === "evict" || !hidden.has(entry.payload.hostId))
77
+ }
78
+ };
79
+ }
80
+ /** `org` needs an owner or admin. The host's owner, or an owner or admin, may set `member`. */
81
+ async function setHostVisibility(subject, org, hostId, visibility) {
82
+ if (visibility !== "org" && visibility !== "member") throw new GlobalTierRefusal(400, "Invalid visibility");
83
+ return database.transaction(async (tx) => {
84
+ const role = await membership(tx, subject, org);
85
+ const host = await tx.get("SELECT h.subject FROM identity_roster_host h JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject WHERE h.networkId = ? AND h.hostId = ? AND h.evicted = 0", org, hostId);
86
+ const manager = role === "owner" || role === "admin";
87
+ if (!host || !manager && host.subject !== subject) throw new GlobalTierRefusal(404, "Host unavailable");
88
+ if (visibility === "org" && !manager) throw new GlobalTierRefusal(403, "Owner or admin required");
89
+ const updatedAt = now();
90
+ await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, hostId) DO UPDATE SET visibility = excluded.visibility, setBy = excluded.setBy, updatedAt = excluded.updatedAt", org, hostId, visibility, subject, updatedAt);
91
+ return {
92
+ hostId,
93
+ visibility,
94
+ setBy: subject,
95
+ updatedAt
96
+ };
97
+ });
98
+ }
99
+ return {
100
+ readMemberSettings,
101
+ writeMemberSettings,
102
+ visibleHosts,
103
+ memberRosterView,
104
+ setHostVisibility
105
+ };
106
+ }
107
+ //#endregion
108
+ export { GlobalTierRefusal, MEMBER_SETTINGS_MAX_BYTES, createGlobalTier };
@@ -1,6 +1,7 @@
1
1
  const require_apiContracts = require("../../apiContracts.cjs");
2
2
  const require_index = require("../appleTokens/index.cjs");
3
3
  const require_index$1 = require("../sqliteAdapter/index.cjs");
4
+ const require_globalTier = require("./globalTier.cjs");
4
5
  const require_roster = require("./roster.cjs");
5
6
  let node_crypto = require("node:crypto");
6
7
  let _agimon_ai_po_core = require("@agimon-ai/po-core");
@@ -25,6 +26,10 @@ var IdentityRefusal = class extends Error {
25
26
  this.status = status;
26
27
  }
27
28
  };
29
+ /** Applies `rule` (or Better Auth's default for the path) only when Cloudflare names the client. */
30
+ function perClientLimit(rule) {
31
+ return (request, current) => request.headers.get("cf-connecting-ip") ? rule ?? current : false;
32
+ }
28
33
  async function createIdentityHome(config, ports) {
29
34
  if (config.jwtKeyWrap.length < 32) throw new Error("Identity key-wrap secret must contain at least 32 characters");
30
35
  const now = ports.now ?? Date.now;
@@ -45,6 +50,22 @@ async function createIdentityHome(config, ports) {
45
50
  "/delete-user/callback"
46
51
  ],
47
52
  trustedOrigins: [config.issuer, "po://"],
53
+ rateLimit: {
54
+ enabled: true,
55
+ storage: "database",
56
+ customRules: {
57
+ "/email-otp/send-verification-otp": perClientLimit({
58
+ window: 60,
59
+ max: 3
60
+ }),
61
+ "/sign-in/email-otp": perClientLimit({
62
+ window: 60,
63
+ max: 3
64
+ }),
65
+ "/**": perClientLimit()
66
+ }
67
+ },
68
+ advanced: { ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] } },
48
69
  logger: { disabled: true },
49
70
  account: {
50
71
  encryptOAuthTokens: true,
@@ -53,6 +74,15 @@ async function createIdentityHome(config, ports) {
53
74
  socialProviders,
54
75
  plugins: [
55
76
  (0, better_auth_plugins.organization)({
77
+ allowUserToCreateOrganization: true,
78
+ requireEmailVerificationOnInvitation: true,
79
+ async sendInvitationEmail({ id, email, organization: invitedTo, inviter }) {
80
+ await ports.email.send({
81
+ to: email,
82
+ subject: `Join ${invitedTo.name} on Po`,
83
+ text: `${inviter.user.name || inviter.user.email} invited you to ${invitedTo.name}. Sign in to Po with this address and accept invitation ${id}.`
84
+ });
85
+ },
56
86
  ac,
57
87
  roles: {
58
88
  owner: ac.newRole(better_auth_plugins_organization_access.ownerAc.statements),
@@ -69,13 +99,17 @@ async function createIdentityHome(config, ports) {
69
99
  jwt: { issuer: config.issuer }
70
100
  }),
71
101
  (0, _better_auth_expo.expo)(),
72
- (0, better_auth_plugins.emailOTP)({ async sendVerificationOTP({ email, otp }) {
73
- await ports.email.send({
74
- to: email,
75
- subject: "Your Po code",
76
- text: otp
77
- });
78
- } }),
102
+ (0, better_auth_plugins.emailOTP)({
103
+ expiresIn: 300,
104
+ allowedAttempts: 3,
105
+ async sendVerificationOTP({ email, otp }) {
106
+ await ports.email.send({
107
+ to: email,
108
+ subject: "Your Po code",
109
+ text: otp
110
+ });
111
+ }
112
+ }),
79
113
  (0, better_auth_plugins.magicLink)({ async sendMagicLink({ email, url }) {
80
114
  await ports.email.send({
81
115
  to: email,
@@ -187,6 +221,18 @@ async function createIdentityHome(config, ports) {
187
221
  "ALTER TABLE identity_approval ADD COLUMN requestedAt INTEGER",
188
222
  "ALTER TABLE identity_approval ADD COLUMN rejected INTEGER NOT NULL DEFAULT 0"
189
223
  ]
224
+ },
225
+ {
226
+ version: 9,
227
+ statements: ["CREATE TABLE IF NOT EXISTS \"rateLimit\" (\"id\" TEXT PRIMARY KEY, \"key\" TEXT NOT NULL UNIQUE, \"count\" INTEGER NOT NULL, \"lastRequest\" INTEGER NOT NULL)"]
228
+ },
229
+ {
230
+ version: 10,
231
+ statements: [
232
+ "CREATE TABLE IF NOT EXISTS member_settings (org TEXT NOT NULL, subject TEXT NOT NULL, yaml TEXT NOT NULL, hash TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, subject))",
233
+ "CREATE TABLE IF NOT EXISTS host_visibility (org TEXT NOT NULL, hostId TEXT NOT NULL, visibility TEXT NOT NULL CHECK(visibility IN ('org','member')), setBy TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, hostId))",
234
+ "CREATE TRIGGER IF NOT EXISTS member_settings_member_remove AFTER DELETE ON member BEGIN DELETE FROM member_settings WHERE org = OLD.organizationId AND subject = OLD.userId; END"
235
+ ]
190
236
  }
191
237
  ], { table: "identity_registry_migrations" });
192
238
  const auth = (0, better_auth.betterAuth)({
@@ -194,6 +240,7 @@ async function createIdentityHome(config, ports) {
194
240
  database: require_index$1.poAdapter(database)
195
241
  });
196
242
  const roster = await require_roster.createIssuerRoster(database, config.issuer, config.jwtKeyWrap, now, membership);
243
+ const globalTier = require_globalTier.createGlobalTier(database, now, membership);
197
244
  async function membership(tx, subject, org) {
198
245
  const person = await tx.get("SELECT id FROM user WHERE id = ?", subject);
199
246
  const member = await tx.get("SELECT role FROM member WHERE userId = ? AND organizationId = ?", subject, org);
@@ -781,6 +828,7 @@ async function createIdentityHome(config, ports) {
781
828
  await tx.run("DELETE FROM identity_outbox WHERE kind='materialize-workspace' AND json_extract(payload,'$.orgId')=?", org);
782
829
  for (const table of ["member", "invitation"]) await tx.run(`DELETE FROM ${table} WHERE organizationId=?`, org);
783
830
  await tx.run("DELETE FROM identity_workspace WHERE orgId=?", org);
831
+ for (const table of ["member_settings", "host_visibility"]) await tx.run(`DELETE FROM ${table} WHERE org=?`, org);
784
832
  await tx.run("DELETE FROM identity_personal_org WHERE organizationId=?", org);
785
833
  await tx.run("DELETE FROM first_workspace WHERE organizationId=?", org);
786
834
  await tx.run("DELETE FROM organization WHERE id=?", org);
@@ -950,6 +998,37 @@ async function createIdentityHome(config, ports) {
950
998
  const text = new TextDecoder().decode(bytes);
951
999
  return json ? JSON.parse(text) : text;
952
1000
  }
1001
+ /**
1002
+ * Caller of an issuer route: a C1 identity token bound to a current device, or a Better Auth session
1003
+ * cookie. Cookie writes also need `x-po-csrf: 1`, which a cross-site form cannot send.
1004
+ */
1005
+ async function requestSubject(request, audience, mutating = false) {
1006
+ const origin = request.headers.get("origin");
1007
+ if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
1008
+ const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
1009
+ if (!token) {
1010
+ if (mutating && request.headers.get("x-po-csrf") !== "1") throw new IdentityRefusal(403, "CSRF header required");
1011
+ const subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
1012
+ if (!subject) throw new IdentityRefusal(401, "Sign in required");
1013
+ return subject;
1014
+ }
1015
+ try {
1016
+ const jwks = await auth.api.getJwks();
1017
+ const { payload } = await (0, jose.jwtVerify)(token, (0, jose.createLocalJWKSet)(jwks), {
1018
+ issuer: config.issuer,
1019
+ ...audience === void 0 ? {} : { audience },
1020
+ algorithms: ["ES256"],
1021
+ currentDate: new Date(now() + 3e4)
1022
+ });
1023
+ if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
1024
+ const cnf = payload.cnf;
1025
+ if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
1026
+ await orgRole(payload.sub, payload.org);
1027
+ return payload.sub;
1028
+ } catch {
1029
+ throw new IdentityRefusal(401, "Current identity token required");
1030
+ }
1031
+ }
953
1032
  async function fetchHandler(request) {
954
1033
  let path;
955
1034
  try {
@@ -966,44 +1045,50 @@ async function createIdentityHome(config, ports) {
966
1045
  const own = path === "/api/networks/own-hub-link";
967
1046
  const remove = path === "/api/networks/remove-hub";
968
1047
  if (path === "/api/networks/hub-removal-receipt" && request.method === "GET") return Response.json(await roster.removalReceiptFromHost(request), { headers: { "cache-control": "no-store" } });
1048
+ const visible = /^\/api\/networks\/([^/]+)\/hosts\/visible$/.exec(path);
1049
+ const visibility = /^\/api\/networks\/([^/]+)\/hosts\/([^/]+)\/visibility$/.exec(path);
1050
+ if (visible && request.method === "GET") return Response.json(await globalTier.visibleHosts(await requestSubject(request, visible[1]), visible[1]), { headers: { "cache-control": "no-store" } });
1051
+ if (visibility && request.method === "PUT") {
1052
+ const subject = await requestSubject(request, visibility[1], true);
1053
+ const body = await readBody(request);
1054
+ return Response.json(await globalTier.setHostVisibility(subject, visibility[1], visibility[2], body?.visibility));
1055
+ }
1056
+ if (visible || visibility) return new Response("Method not allowed", { status: 405 });
969
1057
  if (!match && !own && !remove) return new Response("not found", { status: 404 });
970
1058
  if (match?.[2] === "roster" && request.method === "GET" && request.headers.has("x-po-roster-proof")) return Response.json(await roster.rosterFromHost(request, match[1]), { headers: { "cache-control": "no-store" } });
971
- const origin = request.headers.get("origin");
972
- if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
973
- let subject;
974
- const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
975
- if (token) try {
976
- const jwks = await auth.api.getJwks();
977
- const { payload } = await (0, jose.jwtVerify)(token, (0, jose.createLocalJWKSet)(jwks), {
978
- issuer: config.issuer,
979
- ...match ? { audience: match[1] } : {},
980
- algorithms: ["ES256"],
981
- currentDate: new Date(now() + 3e4)
982
- });
983
- if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
984
- const cnf = payload.cnf;
985
- if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
986
- await orgRole(payload.sub, payload.org);
987
- subject = payload.sub;
988
- } catch {
989
- throw new IdentityRefusal(401, "Current identity token required");
990
- }
991
- else subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
992
- if (!subject) throw new IdentityRefusal(401, "Sign in required");
1059
+ const subject = await requestSubject(request, match?.[1]);
993
1060
  if (own && request.method === "POST") return Response.json({ networkId: await personalOrg(subject) });
994
1061
  if (remove && request.method === "POST") return Response.json(await roster.removeHub(subject, await readBody(request)), { headers: { "cache-control": "no-store" } });
995
- if (match?.[2] === "roster" && request.method === "GET") return Response.json(await roster.networkRoster(subject, match[1]), { headers: { "cache-control": "no-store" } });
1062
+ if (match?.[2] === "roster" && request.method === "GET") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.networkRoster(subject, match[1])), { headers: { "cache-control": "no-store" } });
996
1063
  if (match && request.method === "POST") {
997
1064
  const body = await readBody(request);
998
- if (match[2] === "hosts") return Response.json(await roster.registerRosterHost(subject, match[1], body?.entry));
999
- if (match[2] === "changes") return Response.json(await roster.registerRosterChange(subject, match[1], body?.change));
1065
+ if (match[2] === "hosts") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterHost(subject, match[1], body?.entry)));
1066
+ if (match[2] === "changes") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterChange(subject, match[1], body?.change)));
1000
1067
  }
1001
1068
  return new Response("Method not allowed", { status: 405 });
1002
1069
  } catch (error) {
1003
- if (error instanceof IdentityRefusal || error instanceof require_roster.RosterRefusal) return Response.json({ error: error.message }, { status: error.status });
1070
+ if (error instanceof IdentityRefusal || error instanceof require_roster.RosterRefusal || error instanceof require_globalTier.GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
1004
1071
  if (error instanceof SyntaxError || error instanceof TypeError) return Response.json({ error: "Invalid roster request" }, { status: 400 });
1005
1072
  throw error;
1006
1073
  }
1074
+ if (path === "/api/account/settings") try {
1075
+ const query = new URL(request.url).searchParams;
1076
+ const org = query.get("org") ?? "";
1077
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(org)) throw new IdentityRefusal(400, "Organization required");
1078
+ const headers = { "cache-control": "no-store" };
1079
+ if (request.method === "GET") return Response.json(await globalTier.readMemberSettings(await requestSubject(request, org), org), { headers });
1080
+ if (request.method === "PUT") {
1081
+ const subject = await requestSubject(request, org, true);
1082
+ const expectedHash = query.get("expectedHash");
1083
+ if (!expectedHash) throw new IdentityRefusal(428, "expectedHash required");
1084
+ const yaml = await readBody(request, false);
1085
+ return Response.json(await globalTier.writeMemberSettings(subject, org, yaml, expectedHash), { headers });
1086
+ }
1087
+ return new Response("Method not allowed", { status: 405 });
1088
+ } catch (error) {
1089
+ if (error instanceof IdentityRefusal || error instanceof require_globalTier.GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
1090
+ throw error;
1091
+ }
1007
1092
  if (!path.startsWith("/api/auth/")) return new Response("not found", { status: 404 });
1008
1093
  if (path.replace(/\/+$/, "") === "/api/auth/token") return new Response("Device signature required", { status: 401 });
1009
1094
  if (path === "/api/auth/device-key" && request.method === "POST") {
@@ -1214,6 +1299,7 @@ async function createIdentityHome(config, ports) {
1214
1299
  return {
1215
1300
  database,
1216
1301
  ...roster,
1302
+ memberRosterView: globalTier.memberRosterView,
1217
1303
  fetch: fetchHandler,
1218
1304
  personalOrg,
1219
1305
  ensurePersonalOrg,
@@ -1,4 +1,5 @@
1
1
  import { IdentityProof, IdentityProvisioningItem, IdentityWorkspaceAllocation, PersonalOrgTrigger, identityProofFields } from "../../apiContracts.mjs";
2
+ import { MemberRosterView } from "./globalTier.mjs";
2
3
  import { AppleTokenConfig } from "../appleTokens/index.mjs";
3
4
  import { IdentityEmailSender } from "../emailSender/index.mjs";
4
5
  import { FederationEnvelope } from "@agimon-ai/po-core";
@@ -76,6 +77,7 @@ export declare function createIdentityHome(config: IdentityHomeConfig, ports: Id
76
77
  }, "po/hub-removal-receipt/v1">>;
77
78
  removalReceiptFromHost: (request: Request) => Promise<FederationEnvelope<"po/hub-removal-receipt/v1">>;
78
79
  database: import("@earendil-works/chord/sqlite").SqliteDatabase;
80
+ memberRosterView: (subject: string, org: string, snapshot: import("@agimon-ai/po-web-security").SignedFederationEnvelope<import("@agimon-ai/po-core").FederationRoster, "po/roster/v1">) => Promise<MemberRosterView>;
79
81
  fetch: (request: Request) => Promise<Response>;
80
82
  personalOrg: (subject: string) => Promise<string>;
81
83
  ensurePersonalOrg: (subject: string, trigger: PersonalOrgTrigger) => Promise<IdentityWorkspaceAllocation>;
@@ -1,6 +1,7 @@
1
1
  import { identityProofFields } from "../../apiContracts.mjs";
2
2
  import { appleTokenService } from "../appleTokens/index.mjs";
3
3
  import { openIdentity, poAdapter } from "../sqliteAdapter/index.mjs";
4
+ import { GlobalTierRefusal, createGlobalTier } from "./globalTier.mjs";
4
5
  import { RosterRefusal, createIssuerRoster } from "./roster.mjs";
5
6
  import { createPublicKey } from "node:crypto";
6
7
  import { federationEnrollmentGeneration } from "@agimon-ai/po-core";
@@ -25,6 +26,10 @@ var IdentityRefusal = class extends Error {
25
26
  this.status = status;
26
27
  }
27
28
  };
29
+ /** Applies `rule` (or Better Auth's default for the path) only when Cloudflare names the client. */
30
+ function perClientLimit(rule) {
31
+ return (request, current) => request.headers.get("cf-connecting-ip") ? rule ?? current : false;
32
+ }
28
33
  async function createIdentityHome(config, ports) {
29
34
  if (config.jwtKeyWrap.length < 32) throw new Error("Identity key-wrap secret must contain at least 32 characters");
30
35
  const now = ports.now ?? Date.now;
@@ -45,6 +50,22 @@ async function createIdentityHome(config, ports) {
45
50
  "/delete-user/callback"
46
51
  ],
47
52
  trustedOrigins: [config.issuer, "po://"],
53
+ rateLimit: {
54
+ enabled: true,
55
+ storage: "database",
56
+ customRules: {
57
+ "/email-otp/send-verification-otp": perClientLimit({
58
+ window: 60,
59
+ max: 3
60
+ }),
61
+ "/sign-in/email-otp": perClientLimit({
62
+ window: 60,
63
+ max: 3
64
+ }),
65
+ "/**": perClientLimit()
66
+ }
67
+ },
68
+ advanced: { ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] } },
48
69
  logger: { disabled: true },
49
70
  account: {
50
71
  encryptOAuthTokens: true,
@@ -53,6 +74,15 @@ async function createIdentityHome(config, ports) {
53
74
  socialProviders,
54
75
  plugins: [
55
76
  organization({
77
+ allowUserToCreateOrganization: true,
78
+ requireEmailVerificationOnInvitation: true,
79
+ async sendInvitationEmail({ id, email, organization: invitedTo, inviter }) {
80
+ await ports.email.send({
81
+ to: email,
82
+ subject: `Join ${invitedTo.name} on Po`,
83
+ text: `${inviter.user.name || inviter.user.email} invited you to ${invitedTo.name}. Sign in to Po with this address and accept invitation ${id}.`
84
+ });
85
+ },
56
86
  ac,
57
87
  roles: {
58
88
  owner: ac.newRole(ownerAc.statements),
@@ -69,13 +99,17 @@ async function createIdentityHome(config, ports) {
69
99
  jwt: { issuer: config.issuer }
70
100
  }),
71
101
  expo(),
72
- emailOTP({ async sendVerificationOTP({ email, otp }) {
73
- await ports.email.send({
74
- to: email,
75
- subject: "Your Po code",
76
- text: otp
77
- });
78
- } }),
102
+ emailOTP({
103
+ expiresIn: 300,
104
+ allowedAttempts: 3,
105
+ async sendVerificationOTP({ email, otp }) {
106
+ await ports.email.send({
107
+ to: email,
108
+ subject: "Your Po code",
109
+ text: otp
110
+ });
111
+ }
112
+ }),
79
113
  magicLink({ async sendMagicLink({ email, url }) {
80
114
  await ports.email.send({
81
115
  to: email,
@@ -187,6 +221,18 @@ async function createIdentityHome(config, ports) {
187
221
  "ALTER TABLE identity_approval ADD COLUMN requestedAt INTEGER",
188
222
  "ALTER TABLE identity_approval ADD COLUMN rejected INTEGER NOT NULL DEFAULT 0"
189
223
  ]
224
+ },
225
+ {
226
+ version: 9,
227
+ statements: ["CREATE TABLE IF NOT EXISTS \"rateLimit\" (\"id\" TEXT PRIMARY KEY, \"key\" TEXT NOT NULL UNIQUE, \"count\" INTEGER NOT NULL, \"lastRequest\" INTEGER NOT NULL)"]
228
+ },
229
+ {
230
+ version: 10,
231
+ statements: [
232
+ "CREATE TABLE IF NOT EXISTS member_settings (org TEXT NOT NULL, subject TEXT NOT NULL, yaml TEXT NOT NULL, hash TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, subject))",
233
+ "CREATE TABLE IF NOT EXISTS host_visibility (org TEXT NOT NULL, hostId TEXT NOT NULL, visibility TEXT NOT NULL CHECK(visibility IN ('org','member')), setBy TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, hostId))",
234
+ "CREATE TRIGGER IF NOT EXISTS member_settings_member_remove AFTER DELETE ON member BEGIN DELETE FROM member_settings WHERE org = OLD.organizationId AND subject = OLD.userId; END"
235
+ ]
190
236
  }
191
237
  ], { table: "identity_registry_migrations" });
192
238
  const auth = betterAuth({
@@ -194,6 +240,7 @@ async function createIdentityHome(config, ports) {
194
240
  database: poAdapter(database)
195
241
  });
196
242
  const roster = await createIssuerRoster(database, config.issuer, config.jwtKeyWrap, now, membership);
243
+ const globalTier = createGlobalTier(database, now, membership);
197
244
  async function membership(tx, subject, org) {
198
245
  const person = await tx.get("SELECT id FROM user WHERE id = ?", subject);
199
246
  const member = await tx.get("SELECT role FROM member WHERE userId = ? AND organizationId = ?", subject, org);
@@ -781,6 +828,7 @@ async function createIdentityHome(config, ports) {
781
828
  await tx.run("DELETE FROM identity_outbox WHERE kind='materialize-workspace' AND json_extract(payload,'$.orgId')=?", org);
782
829
  for (const table of ["member", "invitation"]) await tx.run(`DELETE FROM ${table} WHERE organizationId=?`, org);
783
830
  await tx.run("DELETE FROM identity_workspace WHERE orgId=?", org);
831
+ for (const table of ["member_settings", "host_visibility"]) await tx.run(`DELETE FROM ${table} WHERE org=?`, org);
784
832
  await tx.run("DELETE FROM identity_personal_org WHERE organizationId=?", org);
785
833
  await tx.run("DELETE FROM first_workspace WHERE organizationId=?", org);
786
834
  await tx.run("DELETE FROM organization WHERE id=?", org);
@@ -950,6 +998,37 @@ async function createIdentityHome(config, ports) {
950
998
  const text = new TextDecoder().decode(bytes);
951
999
  return json ? JSON.parse(text) : text;
952
1000
  }
1001
+ /**
1002
+ * Caller of an issuer route: a C1 identity token bound to a current device, or a Better Auth session
1003
+ * cookie. Cookie writes also need `x-po-csrf: 1`, which a cross-site form cannot send.
1004
+ */
1005
+ async function requestSubject(request, audience, mutating = false) {
1006
+ const origin = request.headers.get("origin");
1007
+ if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
1008
+ const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
1009
+ if (!token) {
1010
+ if (mutating && request.headers.get("x-po-csrf") !== "1") throw new IdentityRefusal(403, "CSRF header required");
1011
+ const subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
1012
+ if (!subject) throw new IdentityRefusal(401, "Sign in required");
1013
+ return subject;
1014
+ }
1015
+ try {
1016
+ const jwks = await auth.api.getJwks();
1017
+ const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
1018
+ issuer: config.issuer,
1019
+ ...audience === void 0 ? {} : { audience },
1020
+ algorithms: ["ES256"],
1021
+ currentDate: new Date(now() + 3e4)
1022
+ });
1023
+ if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
1024
+ const cnf = payload.cnf;
1025
+ if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
1026
+ await orgRole(payload.sub, payload.org);
1027
+ return payload.sub;
1028
+ } catch {
1029
+ throw new IdentityRefusal(401, "Current identity token required");
1030
+ }
1031
+ }
953
1032
  async function fetchHandler(request) {
954
1033
  let path;
955
1034
  try {
@@ -966,44 +1045,50 @@ async function createIdentityHome(config, ports) {
966
1045
  const own = path === "/api/networks/own-hub-link";
967
1046
  const remove = path === "/api/networks/remove-hub";
968
1047
  if (path === "/api/networks/hub-removal-receipt" && request.method === "GET") return Response.json(await roster.removalReceiptFromHost(request), { headers: { "cache-control": "no-store" } });
1048
+ const visible = /^\/api\/networks\/([^/]+)\/hosts\/visible$/.exec(path);
1049
+ const visibility = /^\/api\/networks\/([^/]+)\/hosts\/([^/]+)\/visibility$/.exec(path);
1050
+ if (visible && request.method === "GET") return Response.json(await globalTier.visibleHosts(await requestSubject(request, visible[1]), visible[1]), { headers: { "cache-control": "no-store" } });
1051
+ if (visibility && request.method === "PUT") {
1052
+ const subject = await requestSubject(request, visibility[1], true);
1053
+ const body = await readBody(request);
1054
+ return Response.json(await globalTier.setHostVisibility(subject, visibility[1], visibility[2], body?.visibility));
1055
+ }
1056
+ if (visible || visibility) return new Response("Method not allowed", { status: 405 });
969
1057
  if (!match && !own && !remove) return new Response("not found", { status: 404 });
970
1058
  if (match?.[2] === "roster" && request.method === "GET" && request.headers.has("x-po-roster-proof")) return Response.json(await roster.rosterFromHost(request, match[1]), { headers: { "cache-control": "no-store" } });
971
- const origin = request.headers.get("origin");
972
- if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
973
- let subject;
974
- const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
975
- if (token) try {
976
- const jwks = await auth.api.getJwks();
977
- const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
978
- issuer: config.issuer,
979
- ...match ? { audience: match[1] } : {},
980
- algorithms: ["ES256"],
981
- currentDate: new Date(now() + 3e4)
982
- });
983
- if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
984
- const cnf = payload.cnf;
985
- if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
986
- await orgRole(payload.sub, payload.org);
987
- subject = payload.sub;
988
- } catch {
989
- throw new IdentityRefusal(401, "Current identity token required");
990
- }
991
- else subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
992
- if (!subject) throw new IdentityRefusal(401, "Sign in required");
1059
+ const subject = await requestSubject(request, match?.[1]);
993
1060
  if (own && request.method === "POST") return Response.json({ networkId: await personalOrg(subject) });
994
1061
  if (remove && request.method === "POST") return Response.json(await roster.removeHub(subject, await readBody(request)), { headers: { "cache-control": "no-store" } });
995
- if (match?.[2] === "roster" && request.method === "GET") return Response.json(await roster.networkRoster(subject, match[1]), { headers: { "cache-control": "no-store" } });
1062
+ if (match?.[2] === "roster" && request.method === "GET") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.networkRoster(subject, match[1])), { headers: { "cache-control": "no-store" } });
996
1063
  if (match && request.method === "POST") {
997
1064
  const body = await readBody(request);
998
- if (match[2] === "hosts") return Response.json(await roster.registerRosterHost(subject, match[1], body?.entry));
999
- if (match[2] === "changes") return Response.json(await roster.registerRosterChange(subject, match[1], body?.change));
1065
+ if (match[2] === "hosts") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterHost(subject, match[1], body?.entry)));
1066
+ if (match[2] === "changes") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterChange(subject, match[1], body?.change)));
1000
1067
  }
1001
1068
  return new Response("Method not allowed", { status: 405 });
1002
1069
  } catch (error) {
1003
- if (error instanceof IdentityRefusal || error instanceof RosterRefusal) return Response.json({ error: error.message }, { status: error.status });
1070
+ if (error instanceof IdentityRefusal || error instanceof RosterRefusal || error instanceof GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
1004
1071
  if (error instanceof SyntaxError || error instanceof TypeError) return Response.json({ error: "Invalid roster request" }, { status: 400 });
1005
1072
  throw error;
1006
1073
  }
1074
+ if (path === "/api/account/settings") try {
1075
+ const query = new URL(request.url).searchParams;
1076
+ const org = query.get("org") ?? "";
1077
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(org)) throw new IdentityRefusal(400, "Organization required");
1078
+ const headers = { "cache-control": "no-store" };
1079
+ if (request.method === "GET") return Response.json(await globalTier.readMemberSettings(await requestSubject(request, org), org), { headers });
1080
+ if (request.method === "PUT") {
1081
+ const subject = await requestSubject(request, org, true);
1082
+ const expectedHash = query.get("expectedHash");
1083
+ if (!expectedHash) throw new IdentityRefusal(428, "expectedHash required");
1084
+ const yaml = await readBody(request, false);
1085
+ return Response.json(await globalTier.writeMemberSettings(subject, org, yaml, expectedHash), { headers });
1086
+ }
1087
+ return new Response("Method not allowed", { status: 405 });
1088
+ } catch (error) {
1089
+ if (error instanceof IdentityRefusal || error instanceof GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
1090
+ throw error;
1091
+ }
1007
1092
  if (!path.startsWith("/api/auth/")) return new Response("not found", { status: 404 });
1008
1093
  if (path.replace(/\/+$/, "") === "/api/auth/token") return new Response("Device signature required", { status: 401 });
1009
1094
  if (path === "/api/auth/device-key" && request.method === "POST") {
@@ -1214,6 +1299,7 @@ async function createIdentityHome(config, ports) {
1214
1299
  return {
1215
1300
  database,
1216
1301
  ...roster,
1302
+ memberRosterView: globalTier.memberRosterView,
1217
1303
  fetch: fetchHandler,
1218
1304
  personalOrg,
1219
1305
  ensurePersonalOrg,
@@ -108,6 +108,7 @@ async function createIssuerRoster(database, issuer, wrap, now, membership) {
108
108
  await currentEpoch(tx, network);
109
109
  await tx.run("UPDATE identity_roster_epoch SET epoch = epoch + 1 WHERE networkId = ?", network);
110
110
  await tx.run("INSERT INTO identity_roster_host (networkId,hostId,subject,entry,enrollmentGeneration) VALUES (?,?,?,?,?) ON CONFLICT(networkId,hostId) DO UPDATE SET entry=excluded.entry,enrollmentGeneration=excluded.enrollmentGeneration,evicted=0,changedEpoch=NULL", network, p.hostId, subject, JSON.stringify(entry), generation);
111
+ if (!held && !cloud) await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, 'member', ?, ?) ON CONFLICT(org, hostId) DO NOTHING", network, p.hostId, subject, now());
111
112
  return snapshot(tx, network);
112
113
  });
113
114
  }
@@ -108,6 +108,7 @@ async function createIssuerRoster(database, issuer, wrap, now, membership) {
108
108
  await currentEpoch(tx, network);
109
109
  await tx.run("UPDATE identity_roster_epoch SET epoch = epoch + 1 WHERE networkId = ?", network);
110
110
  await tx.run("INSERT INTO identity_roster_host (networkId,hostId,subject,entry,enrollmentGeneration) VALUES (?,?,?,?,?) ON CONFLICT(networkId,hostId) DO UPDATE SET entry=excluded.entry,enrollmentGeneration=excluded.enrollmentGeneration,evicted=0,changedEpoch=NULL", network, p.hostId, subject, JSON.stringify(entry), generation);
111
+ if (!held && !cloud) await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, 'member', ?, ?) ON CONFLICT(org, hostId) DO NOTHING", network, p.hostId, subject, now());
111
112
  return snapshot(tx, network);
112
113
  });
113
114
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-identity",
3
- "version": "0.0.2-alpha.9",
3
+ "version": "0.0.2-alpha.90",
4
4
  "description": "Portable identity home for Po",
5
5
  "keywords": [
6
6
  "ai",
@@ -47,19 +47,19 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@agimon-ai/po-core": "0.0.0-alpha.62",
51
- "@agimon-ai/po-web-security": "0.0.0-alpha.62",
50
+ "@agimon-ai/po-core": "0.0.0-alpha.143",
51
+ "@agimon-ai/po-web-security": "0.0.0-alpha.143",
52
52
  "@better-auth/expo": "1.7.12",
53
53
  "@better-auth/passkey": "1.7.12",
54
54
  "@better-auth/sso": "1.7.12",
55
- "@earendil-works/chord": "1.4.0",
56
- "@earendil-works/pi-durable": "1.4.0",
55
+ "@earendil-works/chord": "1.5.1",
56
+ "@earendil-works/pi-durable": "1.5.1",
57
57
  "better-auth": "1.7.12",
58
58
  "jose": "6.2.2"
59
59
  },
60
60
  "devDependencies": {
61
- "@agimon-ai/po-network": "0.0.2-alpha.9",
62
- "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.62",
61
+ "@agimon-ai/po-network": "0.0.2-alpha.90",
62
+ "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.143",
63
63
  "@types/node": "26.4.1",
64
64
  "tsdown": "0.23.0",
65
65
  "typescript": "7.0.2",
@@ -72,7 +72,7 @@
72
72
  "entry": "./src/extensions/server.ts",
73
73
  "dist": "./dist/extensions/server.mjs",
74
74
  "scopes": [
75
- "global"
75
+ "host"
76
76
  ],
77
77
  "contracts": {
78
78
  "entry": "./src/exports/apiContracts.ts",