@agimon-ai/po-auth-server 0.0.2-alpha.3 → 0.0.2-alpha.5

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.
@@ -4,8 +4,10 @@ Object.defineProperties(exports, {
4
4
  });
5
5
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
6
6
  const require_index = require("../services/identityHome/index.cjs");
7
- const require_index$1 = require("../services/identityConfiguration/index.cjs");
8
- const require_index$2 = require("../services/sharedSpace/index.cjs");
7
+ const require_index$1 = require("../services/identityWebRoutes/index.cjs");
8
+ const require_index$2 = require("../services/identityConfiguration/index.cjs");
9
+ const require_index$3 = require("../services/identityPairing/index.cjs");
10
+ const require_index$4 = require("../services/sharedSpace/index.cjs");
9
11
  let node_path = require("node:path");
10
12
  node_path = require_runtime.__toESM(node_path, 1);
11
13
  let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
@@ -19,7 +21,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
19
21
  host: async (plugin) => {
20
22
  const environment = plugin.host.context.environment;
21
23
  if (!environment) throw new Error("Identity home requires an admitted server environment");
22
- const configuration = require_index$1.identityConfiguration(environment);
24
+ const configuration = require_index$2.identityConfiguration(environment);
23
25
  let home;
24
26
  let timer;
25
27
  let recoveryTimer;
@@ -44,7 +46,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
44
46
  email: configuration.email,
45
47
  reportOverduePurge: () => plugin.host.context.onNotice("Identity Cloud purge overdue; pending work will retry."),
46
48
  purgePersonalOrg: async (org) => {
47
- (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.remove(await require_index$2.sharedSpaceRoot(spaceRoot, org), {
49
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.remove(await require_index$4.sharedSpaceRoot(spaceRoot, org), {
48
50
  recursive: true,
49
51
  force: true
50
52
  }, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
@@ -68,12 +70,13 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
68
70
  await provider.dispose();
69
71
  throw new Error("Identity platform services unavailable");
70
72
  }
71
- const shared = require_index$2.createSharedSpaceProvider({
73
+ const shared = require_index$4.createSharedSpaceProvider({
72
74
  issuer: configuration.config.issuer,
73
75
  spaceRoot,
74
76
  isMember: async (subject, org) => await home?.isOrgMember(subject, org) === true
75
77
  });
76
78
  const space = plugin.context.inject([_agimon_ai_po_core_platform.PO_SPACE_SERVICE], (bound) => (0, _agimon_ai_po_core_platform.readPoSpace)(bound)?.registerProvider(shared));
79
+ const pairing = require_index$3.createIdentityPairing(configuration.config.issuer, home);
77
80
  let teamChanged;
78
81
  let audit;
79
82
  const team = plugin.context.inject([_agimon_ai_po_core_serverPlugin.PO_HOST_TEAM_SERVICE], (bound) => {
@@ -82,6 +85,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
82
85
  const undo = host.setSource({
83
86
  issuer: configuration.config.issuer,
84
87
  team: (owner) => home.ownedTeam(owner),
88
+ pairingAccount: (proof, request) => pairing.consume(proof, request),
85
89
  settings: async (subject, org) => await home.isOrgMember(subject, org) ? { yaml: (await home.readMemberSettings(subject, org)).yaml } : void 0
86
90
  });
87
91
  teamChanged = () => host.changed();
@@ -96,19 +100,21 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
96
100
  * The server stamps the socket peer. Behind trusted proxies the caller is further back, so the proxies' own
97
101
  * forwarded chain goes in front of the peer; without any, a forwarded header is the caller's word and is dropped.
98
102
  */
99
- const answer = (request) => {
103
+ const answer = async (request) => {
100
104
  const forwarded = configuration.trustedProxies.length ? request.headers.get("x-forwarded-for") : null;
101
105
  const peer = request.headers.get(_agimon_ai_po_core_packageApi.PO_API_PEER_ADDRESS_HEADER);
102
- if (!forwarded || !peer) return home.fetch(request);
103
- const headers = new Headers(request.headers);
104
- headers.set(_agimon_ai_po_core_packageApi.PO_API_PEER_ADDRESS_HEADER, `${forwarded}, ${peer}`);
105
- return home.fetch(new Request(request, { headers }));
106
+ if (forwarded && peer) {
107
+ const headers = new Headers(request.headers);
108
+ headers.set(_agimon_ai_po_core_packageApi.PO_API_PEER_ADDRESS_HEADER, `${forwarded}, ${peer}`);
109
+ request = new Request(request, { headers });
110
+ }
111
+ return await pairing.fetch(request) ?? await require_index$1.identityWebResponse(request, home) ?? home.fetch(request);
106
112
  };
107
113
  const fetch = async (request) => {
108
114
  if (request.method === "GET" || request.method === "HEAD") return answer(request);
109
115
  const before = audit ? await home.signedIn(request.headers).catch(() => null) : null;
110
116
  const response = await answer(request);
111
- teamChanged?.();
117
+ if ((response.ok || response.status >= 500) && /^\/api\/auth\/(?:organization\/(?:create|delete|add-member|remove-member|update-member-role|accept-invitation|leave)|delete-user)$/u.test(new URL(request.url).pathname)) teamChanged?.();
112
118
  audit?.({
113
119
  ...before === null ? {} : { actor: {
114
120
  issuer: configuration.config.issuer,
@@ -172,6 +178,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
172
178
  timer = void 0;
173
179
  },
174
180
  onDispose: async () => {
181
+ pairing.clear();
175
182
  await space.dispose();
176
183
  await team.dispose();
177
184
  await provider.dispose();
@@ -1,5 +1,7 @@
1
1
  import { createIdentityHome } from "../services/identityHome/index.mjs";
2
+ import { identityWebResponse } from "../services/identityWebRoutes/index.mjs";
2
3
  import { identityConfiguration } from "../services/identityConfiguration/index.mjs";
4
+ import { createIdentityPairing } from "../services/identityPairing/index.mjs";
3
5
  import { createSharedSpaceProvider, sharedSpaceRoot } from "../services/sharedSpace/index.mjs";
4
6
  import path from "node:path";
5
7
  import { PO_API_PEER_ADDRESS_HEADER } from "@agimon-ai/po-core/packageApi";
@@ -68,6 +70,7 @@ const serverPlugin = defineServerPlugin({
68
70
  isMember: async (subject, org) => await home?.isOrgMember(subject, org) === true
69
71
  });
70
72
  const space = plugin.context.inject([PO_SPACE_SERVICE], (bound) => readPoSpace(bound)?.registerProvider(shared));
73
+ const pairing = createIdentityPairing(configuration.config.issuer, home);
71
74
  let teamChanged;
72
75
  let audit;
73
76
  const team = plugin.context.inject([PO_HOST_TEAM_SERVICE], (bound) => {
@@ -76,6 +79,7 @@ const serverPlugin = defineServerPlugin({
76
79
  const undo = host.setSource({
77
80
  issuer: configuration.config.issuer,
78
81
  team: (owner) => home.ownedTeam(owner),
82
+ pairingAccount: (proof, request) => pairing.consume(proof, request),
79
83
  settings: async (subject, org) => await home.isOrgMember(subject, org) ? { yaml: (await home.readMemberSettings(subject, org)).yaml } : void 0
80
84
  });
81
85
  teamChanged = () => host.changed();
@@ -90,19 +94,21 @@ const serverPlugin = defineServerPlugin({
90
94
  * The server stamps the socket peer. Behind trusted proxies the caller is further back, so the proxies' own
91
95
  * forwarded chain goes in front of the peer; without any, a forwarded header is the caller's word and is dropped.
92
96
  */
93
- const answer = (request) => {
97
+ const answer = async (request) => {
94
98
  const forwarded = configuration.trustedProxies.length ? request.headers.get("x-forwarded-for") : null;
95
99
  const peer = request.headers.get(PO_API_PEER_ADDRESS_HEADER);
96
- if (!forwarded || !peer) return home.fetch(request);
97
- const headers = new Headers(request.headers);
98
- headers.set(PO_API_PEER_ADDRESS_HEADER, `${forwarded}, ${peer}`);
99
- return home.fetch(new Request(request, { headers }));
100
+ if (forwarded && peer) {
101
+ const headers = new Headers(request.headers);
102
+ headers.set(PO_API_PEER_ADDRESS_HEADER, `${forwarded}, ${peer}`);
103
+ request = new Request(request, { headers });
104
+ }
105
+ return await pairing.fetch(request) ?? await identityWebResponse(request, home) ?? home.fetch(request);
100
106
  };
101
107
  const fetch = async (request) => {
102
108
  if (request.method === "GET" || request.method === "HEAD") return answer(request);
103
109
  const before = audit ? await home.signedIn(request.headers).catch(() => null) : null;
104
110
  const response = await answer(request);
105
- teamChanged?.();
111
+ if ((response.ok || response.status >= 500) && /^\/api\/auth\/(?:organization\/(?:create|delete|add-member|remove-member|update-member-role|accept-invitation|leave)|delete-user)$/u.test(new URL(request.url).pathname)) teamChanged?.();
106
112
  audit?.({
107
113
  ...before === null ? {} : { actor: {
108
114
  issuer: configuration.config.issuer,
@@ -166,6 +172,7 @@ const serverPlugin = defineServerPlugin({
166
172
  timer = void 0;
167
173
  },
168
174
  onDispose: async () => {
175
+ pairing.clear();
169
176
  await space.dispose();
170
177
  await team.dispose();
171
178
  await provider.dispose();
package/dist/index.cjs CHANGED
@@ -3,10 +3,14 @@ const require_index = require("./services/appleTokens/index.cjs");
3
3
  const require_index$1 = require("./services/sqliteAdapter/index.cjs");
4
4
  const require_index$2 = require("./services/identityHome/index.cjs");
5
5
  const require_index$3 = require("./services/emailSender/index.cjs");
6
- const require_index$4 = require("./services/identityConfiguration/index.cjs");
6
+ const require_index$4 = require("./services/authWebPages/index.cjs");
7
+ const require_index$5 = require("./services/identityConfiguration/index.cjs");
8
+ const require_index$6 = require("./services/identityPairing/index.cjs");
9
+ exports.AuthWebPages = require_index$4.AuthWebPages;
7
10
  exports.appleTokenService = require_index.appleTokenService;
8
11
  exports.createIdentityHome = require_index$2.createIdentityHome;
9
- exports.identityConfiguration = require_index$4.identityConfiguration;
12
+ exports.createIdentityPairing = require_index$6.createIdentityPairing;
13
+ exports.identityConfiguration = require_index$5.identityConfiguration;
10
14
  exports.openIdentity = require_index$1.openIdentity;
11
15
  exports.poAdapter = require_index$1.poAdapter;
12
16
  exports.unsendboxEmailSender = require_index$3.unsendboxEmailSender;
package/dist/index.d.mts CHANGED
@@ -4,4 +4,7 @@ import { IdentityEmailSender, unsendboxEmailSender } from "./services/emailSende
4
4
  import { IdentityHomeConfig, IdentityHomePorts, createIdentityHome } from "./services/identityHome/index.mjs";
5
5
  import { openIdentity, poAdapter } from "./services/sqliteAdapter/index.mjs";
6
6
  import { IdentityEnvironment, identityConfiguration } from "./services/identityConfiguration/index.mjs";
7
- export { type AppleTokenConfig, type IdentityEmailSender, type IdentityEnvironment, type IdentityHomeConfig, type IdentityHomePorts, type IdentityProvisioningApi, type IdentityProvisioningItem, type IdentityWorkspaceAllocation, type PersonalOrgTrigger, appleTokenService, createIdentityHome, identityConfiguration, openIdentity, poAdapter, unsendboxEmailSender };
7
+ import { AuthOrgChoice, AuthSignInMethods, AuthWebRoutes } from "./services/authWebPages/type.mjs";
8
+ import { AuthWebPages } from "./services/authWebPages/index.mjs";
9
+ import { createIdentityPairing } from "./services/identityPairing/index.mjs";
10
+ export { type AppleTokenConfig, type AuthOrgChoice, type AuthSignInMethods, AuthWebPages, type AuthWebRoutes, type IdentityEmailSender, type IdentityEnvironment, type IdentityHomeConfig, type IdentityHomePorts, type IdentityProvisioningApi, type IdentityProvisioningItem, type IdentityWorkspaceAllocation, type PersonalOrgTrigger, appleTokenService, createIdentityHome, createIdentityPairing, identityConfiguration, openIdentity, poAdapter, unsendboxEmailSender };
package/dist/index.mjs CHANGED
@@ -2,5 +2,7 @@ import { appleTokenService } from "./services/appleTokens/index.mjs";
2
2
  import { openIdentity, poAdapter } from "./services/sqliteAdapter/index.mjs";
3
3
  import { createIdentityHome } from "./services/identityHome/index.mjs";
4
4
  import { unsendboxEmailSender } from "./services/emailSender/index.mjs";
5
+ import { AuthWebPages } from "./services/authWebPages/index.mjs";
5
6
  import { identityConfiguration } from "./services/identityConfiguration/index.mjs";
6
- export { appleTokenService, createIdentityHome, identityConfiguration, openIdentity, poAdapter, unsendboxEmailSender };
7
+ import { createIdentityPairing } from "./services/identityPairing/index.mjs";
8
+ export { AuthWebPages, appleTokenService, createIdentityHome, createIdentityPairing, identityConfiguration, openIdentity, poAdapter, unsendboxEmailSender };
@@ -0,0 +1,154 @@
1
+ //#region src/services/authWebPages/index.ts
2
+ /** Same palette as the stock self-host sign-in page, so the hosted pages read as part of Po. */
3
+ const BASE_STYLE = `body{margin:0;min-height:100dvh;display:grid;place-items:center;font:16px/1.5 ui-sans-serif,system-ui,sans-serif;background:#14161a;color:#e6e8ec}
4
+ main{display:flex;flex-direction:column;gap:1rem;width:min(28rem,90vw);padding:2rem 0}form{display:flex;flex-direction:column;gap:.75rem}
5
+ label{display:flex;flex-direction:column;gap:.35rem;color:#a2a8b4;font-size:.9rem}
6
+ input,select,button{font:inherit;padding:.75rem;border-radius:.6rem;border:1px solid #2c313a}input,select{background:#1b1e24;color:inherit}
7
+ button{background:#2b7a62;border-color:#2b7a62;color:#fff;font-weight:650;cursor:pointer}button.secondary{background:transparent;border-color:#2c313a;color:inherit}
8
+ h1,h2{margin:0}h2{font-size:1.1rem}p{margin:0;color:#a2a8b4}a{color:#6fd3b0}[role=alert]{color:#ff7b7b}[role=status]{color:#6fd3b0}[hidden]{display:none!important}
9
+ section{display:flex;flex-direction:column;gap:.75rem;padding:1rem;border:1px solid #2c313a;border-radius:.8rem}.row{display:flex;gap:.5rem}.row>*{flex:1}
10
+ ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:.75rem}li{display:flex;align-items:center;justify-content:space-between;gap:.75rem}
11
+ li>div{min-width:0;overflow-wrap:anywhere}li button{padding:.4rem .75rem}.muted{color:#a2a8b4;font-size:.9rem}`;
12
+ /** Element lookup, status and error lines, and better-auth's error text, shared by every page script. */
13
+ const HELPERS = `const $=(id)=>document.getElementById(id);const status=$('status');const error=$('error');
14
+ const say=(message,isError)=>{status.textContent=isError?'':message;error.textContent=isError?message:'';};
15
+ const failed=async(response)=>{const text=await response.text();try{const body=JSON.parse(text);return body.message||body.error||text}catch{return text||'Request failed ('+response.status+')'}};`;
16
+ /** A value embedded in a page script as a JS string literal that cannot close the script element. */
17
+ const literal = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
18
+ /** Server-rendered, nonce-locked pages a signed-out or settings-only browser can load without the web bundle. */
19
+ var AuthWebPages = class {
20
+ routes;
21
+ nonce;
22
+ constructor(routes, nonce = randomNonce) {
23
+ this.routes = routes;
24
+ this.nonce = nonce;
25
+ }
26
+ /**
27
+ * Email and password with sign-up, magic link, and Google or GitHub only when the Worker has their credentials.
28
+ * `next` is where a signed-in browser goes; the gateway only passes its own invitation pages.
29
+ */
30
+ signIn(methods, next = "/") {
31
+ const { authBase } = this.routes;
32
+ const socialButtons = ["google", "github"].filter((provider) => methods[provider]).map((provider) => `<button type="button" class="secondary" data-provider="${provider}">Continue with ${provider === "google" ? "Google" : "GitHub"}</button>`).join("");
33
+ return this.#page("Sign in to Po", `<main><h1>Sign in to Po</h1>
34
+ ${socialButtons ? `<section>${socialButtons}</section>` : ""}
35
+ <form id="password-form"${methods.emailPassword ? "" : " hidden"}>
36
+ <label>Email<input id="email" type="email" autocomplete="email" required></label>
37
+ <label id="name-field" hidden>Name<input id="name" autocomplete="name"></label>
38
+ <label>Password<input id="password" type="password" autocomplete="current-password" minlength="8" required></label>
39
+ <button type="submit" id="password-submit">Sign in</button>
40
+ <button type="button" class="secondary" id="mode">Create an account</button></form>
41
+ <form id="link-form"${methods.magicLink ? "" : " hidden"}><p>Or get a sign-in link by email.</p>
42
+ <label>Email<input id="link-email" type="email" autocomplete="email" required></label>
43
+ <button type="submit" class="secondary">Email me a link</button></form>
44
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}let signUp=false;const next=${literal(next)};
45
+ const back='${this.routes.signIn}'+(next==='/'?'':'?next='+encodeURIComponent(next));
46
+ const post=(path,body)=>fetch('${authBase}'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
47
+ const params=new URLSearchParams(location.search);if(params.get('error'))say('That link did not work. It may have expired. Request a new one.',true);
48
+ if(params.get('verified'))say('Email confirmed. Sign in to continue.',false);
49
+ $('mode').addEventListener('click',()=>{signUp=!signUp;$('name-field').hidden=!signUp;
50
+ $('password').autocomplete=signUp?'new-password':'current-password';
51
+ $('password-submit').textContent=signUp?'Create account':'Sign in';$('mode').textContent=signUp?'I already have an account':'Create an account';say('',false);});
52
+ $('password-form').addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const email=$('email').value.trim();
53
+ if(signUp){const response=await post('/sign-up/email',{email,password:$('password').value,name:$('name').value.trim()||email.split('@')[0],callbackURL:back+(next==='/'?'?':'&')+'verified=1'});
54
+ if(!response.ok){say(await failed(response),true);return;}say('Check '+email+' for a link to confirm your email, then sign in.',false);return;}
55
+ const response=await post('/sign-in/email',{email,password:$('password').value});
56
+ if(response.status===403){say('Confirm your email first. We sent a new link to '+email+'.',true);return;}
57
+ if(!response.ok){say(await failed(response),true);return;}location.replace(next);});
58
+ $('link-form').addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const email=$('link-email').value.trim();
59
+ const response=await post('/sign-in/magic-link',{email,callbackURL:next,errorCallbackURL:back});
60
+ if(!response.ok){say(await failed(response),true);return;}say('Check '+email+' for a sign-in link. It expires in 5 minutes.',false);});
61
+ for(const button of document.querySelectorAll('[data-provider]'))button.addEventListener('click',async()=>{say('',false);
62
+ const response=await post('/sign-in/social',{provider:button.dataset.provider,callbackURL:next,errorCallbackURL:back});
63
+ const body=response.ok?await response.json():undefined;if(body&&body.url){location.assign(body.url);return;}say(response.ok?'Sign-in could not start.':await failed(response),true);});`);
64
+ }
65
+ /** Accept or decline one invitation. better-auth only shows it to the person it was sent to. */
66
+ invitation(id) {
67
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
68
+ return this.#page("Join a team on Po", `<main><h1>Join a team on Po</h1><p id="summary">Checking your invitation.</p>
69
+ <div class="row" id="actions" hidden><button type="button" id="accept">Accept</button><button type="button" class="secondary" id="decline">Decline</button></div>
70
+ <button type="button" class="secondary" id="switch" hidden>Sign in with a different email</button>
71
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}const id=${literal(id)};
72
+ const post=(path,body)=>fetch('${authBase}/organization/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
73
+ (async()=>{const response=await fetch('${authBase}/organization/get-invitation?id='+encodeURIComponent(id));
74
+ if(response.status===403){$('summary').textContent=await failed(response);$('switch').hidden=false;return;}
75
+ if(!response.ok){$('summary').textContent='This invitation has expired, was cancelled, or was already used.';return;}
76
+ const invite=await response.json();$('summary').textContent=invite.inviterEmail+' invited you to join '+invite.organizationName+' as '+invite.role+'.';$('actions').hidden=false;})();
77
+ $('accept').addEventListener('click',async()=>{say('',false);const response=await post('accept-invitation',{invitationId:id});
78
+ if(!response.ok){say(await failed(response),true);return;}location.replace('/');});
79
+ $('decline').addEventListener('click',async()=>{say('',false);const response=await post('reject-invitation',{invitationId:id});
80
+ if(!response.ok){say(await failed(response),true);return;}$('actions').hidden=true;$('summary').textContent='You declined the invitation.';});
81
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});
82
+ location.replace('${signIn}?next='+encodeURIComponent(location.pathname));});`);
83
+ }
84
+ /**
85
+ * A signed-in person's first team, or which of their teams this browser uses. Teams are better-auth organizations;
86
+ * the person names a new one and owns it. Afterwards the page goes on to `next`, a path on this site.
87
+ */
88
+ org(mode, orgs, next) {
89
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
90
+ const body = mode === "create" ? `<h1>Name your team</h1><p>Po keeps your sessions and settings in a team. You can invite people to it later.</p>
91
+ <form id="create-form"><label>Team name<input id="name" autocomplete="organization" maxlength="64" required></label>
92
+ <button type="submit">Create team</button></form>` : `<h1>Choose a team</h1><p>You belong to more than one team. Choose the one to use here. To change it later, sign out and sign in again.</p>
93
+ <ul id="orgs"></ul>`;
94
+ return this.#page(mode === "create" ? "Name your team" : "Choose a team", `<main>${body}
95
+ <button type="button" class="secondary" id="switch">Use a different account</button>
96
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}const next=${literal(next)};const orgs=JSON.parse(${literal(JSON.stringify(orgs))});
97
+ const post=(path,body)=>fetch('${authBase}/organization/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
98
+ const use=async(id)=>{const response=await post('set-active',{organizationId:id});if(!response.ok){say(await failed(response),true);return;}location.replace(next);};
99
+ const form=$('create-form');if(form)form.addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const name=$('name').value.trim();if(!name)return;
100
+ const random=Array.from(crypto.getRandomValues(new Uint8Array(4)),(byte)=>byte.toString(16).padStart(2,'0')).join('');
101
+ const slug=(name.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'team')+'-'+random;
102
+ const response=await post('create',{name,slug});if(!response.ok){say(await failed(response),true);return;}await use((await response.json()).id);});
103
+ const list=$('orgs');if(list)list.replaceChildren(...orgs.map((entry)=>{const li=document.createElement('li');const text=document.createElement('div');text.textContent=entry.name;
104
+ const role=document.createElement('div');role.className='muted';role.textContent=entry.role;text.append(role);const button=document.createElement('button');button.type='button';
105
+ button.textContent='Use';button.addEventListener('click',()=>{say('',false);void use(entry.org);});li.append(text,button);return li;}));
106
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});location.replace('${signIn}');});`);
107
+ }
108
+ /**
109
+ * Allow or deny one Po Desktop sign-in. Claiming the code ties it to this person, so only they can answer it, and
110
+ * Desktop gets a session only after Allow. The code is shown so the person can check it matches Desktop's. A person
111
+ * in several teams chooses the one Desktop uses; Desktop never takes the browser's own team.
112
+ */
113
+ device(userCode, email, choice) {
114
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
115
+ return this.#page("Allow Po Desktop?", `<main><h1>Allow Po Desktop?</h1>
116
+ <p>Po Desktop wants to use your Po account <strong id="who"></strong>. Check that it shows this code.</p>
117
+ <label>Code<input id="code" autocomplete="off" spellcheck="false" maxlength="16"></label>
118
+ ${choice ? "<label>Team for Po Desktop<select id=\"org\"></select></label>" : ""}
119
+ <div class="row" id="actions"><button type="button" id="allow">Allow</button><button type="button" class="secondary" id="deny">Deny</button></div>
120
+ <button type="button" class="secondary" id="switch">Use a different account</button>
121
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}$('who').textContent=${literal(email)};const choice=JSON.parse(${literal(JSON.stringify(choice ?? null))});
122
+ if(choice)$('org').replaceChildren(...choice.orgs.map((entry)=>{const option=document.createElement('option');option.value=entry.org;option.textContent=entry.name;option.selected=entry.org===choice.active;return option;}));
123
+ const shown=(code)=>{const clean=code.replace(/[^A-Za-z0-9]/g,'').toUpperCase();return clean.length===8?clean.slice(0,4)+'-'+clean.slice(4):clean;};
124
+ $('code').value=shown(${literal(userCode)});
125
+ const post=(path)=>fetch('${authBase}/device/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({userCode:$('code').value})});
126
+ const answer=async(path,done)=>{say('',false);const claimed=await fetch('${authBase}/device?user_code='+encodeURIComponent($('code').value));
127
+ if(!claimed.ok){say('That code has expired or was already used. Start again from Po Desktop.',true);return;}
128
+ if(path==='approve'&&choice){const chosen=await fetch('${authBase}/device/organization',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({userCode:$('code').value,organizationId:$('org').value})});
129
+ if(!chosen.ok){say(await failed(chosen),true);return;}}
130
+ const response=await post(path);if(!response.ok){say(await failed(response),true);return;}$('actions').hidden=true;$('code').disabled=true;if(choice)$('org').disabled=true;say(done,false);};
131
+ $('allow').addEventListener('click',()=>void answer('approve','Po Desktop is signed in. You can close this tab.'));
132
+ $('deny').addEventListener('click',()=>void answer('deny','Denied. Po Desktop stays signed out. You can close this tab.'));
133
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});
134
+ location.replace('${signIn}?next='+encodeURIComponent(location.pathname+'?user_code='+encodeURIComponent($('code').value)));});`);
135
+ }
136
+ #page(title, body, script) {
137
+ const nonce = this.nonce();
138
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
139
+ <meta name="robots" content="noindex, nofollow"><title>${title}</title><style nonce="${nonce}">${BASE_STYLE}</style></head>
140
+ <body>${body}<script nonce="${nonce}">${script}<\/script></body></html>`;
141
+ return new Response(html, { headers: {
142
+ "content-type": "text/html; charset=utf-8",
143
+ "cache-control": "no-store",
144
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'`,
145
+ "x-content-type-options": "nosniff",
146
+ "referrer-policy": "no-referrer"
147
+ } });
148
+ }
149
+ };
150
+ function randomNonce() {
151
+ return btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
152
+ }
153
+ //#endregion
154
+ exports.AuthWebPages = AuthWebPages;
@@ -0,0 +1,31 @@
1
+ import { AuthOrgChoice, AuthSignInMethods, AuthWebRoutes } from "./type.mjs";
2
+ //#region src/services/authWebPages/index.d.ts
3
+ /** Server-rendered, nonce-locked pages a signed-out or settings-only browser can load without the web bundle. */
4
+ export declare class AuthWebPages {
5
+ #private;
6
+ private readonly routes;
7
+ private readonly nonce;
8
+ constructor(routes: AuthWebRoutes, nonce?: () => string);
9
+ /**
10
+ * Email and password with sign-up, magic link, and Google or GitHub only when the Worker has their credentials.
11
+ * `next` is where a signed-in browser goes; the gateway only passes its own invitation pages.
12
+ */
13
+ signIn(methods: AuthSignInMethods, next?: string): Response;
14
+ /** Accept or decline one invitation. better-auth only shows it to the person it was sent to. */
15
+ invitation(id: string): Response;
16
+ /**
17
+ * A signed-in person's first team, or which of their teams this browser uses. Teams are better-auth organizations;
18
+ * the person names a new one and owns it. Afterwards the page goes on to `next`, a path on this site.
19
+ */
20
+ org(mode: 'create' | 'choose', orgs: AuthOrgChoice[], next: string): Response;
21
+ /**
22
+ * Allow or deny one Po Desktop sign-in. Claiming the code ties it to this person, so only they can answer it, and
23
+ * Desktop gets a session only after Allow. The code is shown so the person can check it matches Desktop's. A person
24
+ * in several teams chooses the one Desktop uses; Desktop never takes the browser's own team.
25
+ */
26
+ device(userCode: string, email: string, choice?: {
27
+ orgs: AuthOrgChoice[];
28
+ active: string | null;
29
+ }): Response;
30
+ }
31
+ //#endregion
@@ -0,0 +1,154 @@
1
+ //#region src/services/authWebPages/index.ts
2
+ /** Same palette as the stock self-host sign-in page, so the hosted pages read as part of Po. */
3
+ const BASE_STYLE = `body{margin:0;min-height:100dvh;display:grid;place-items:center;font:16px/1.5 ui-sans-serif,system-ui,sans-serif;background:#14161a;color:#e6e8ec}
4
+ main{display:flex;flex-direction:column;gap:1rem;width:min(28rem,90vw);padding:2rem 0}form{display:flex;flex-direction:column;gap:.75rem}
5
+ label{display:flex;flex-direction:column;gap:.35rem;color:#a2a8b4;font-size:.9rem}
6
+ input,select,button{font:inherit;padding:.75rem;border-radius:.6rem;border:1px solid #2c313a}input,select{background:#1b1e24;color:inherit}
7
+ button{background:#2b7a62;border-color:#2b7a62;color:#fff;font-weight:650;cursor:pointer}button.secondary{background:transparent;border-color:#2c313a;color:inherit}
8
+ h1,h2{margin:0}h2{font-size:1.1rem}p{margin:0;color:#a2a8b4}a{color:#6fd3b0}[role=alert]{color:#ff7b7b}[role=status]{color:#6fd3b0}[hidden]{display:none!important}
9
+ section{display:flex;flex-direction:column;gap:.75rem;padding:1rem;border:1px solid #2c313a;border-radius:.8rem}.row{display:flex;gap:.5rem}.row>*{flex:1}
10
+ ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:.75rem}li{display:flex;align-items:center;justify-content:space-between;gap:.75rem}
11
+ li>div{min-width:0;overflow-wrap:anywhere}li button{padding:.4rem .75rem}.muted{color:#a2a8b4;font-size:.9rem}`;
12
+ /** Element lookup, status and error lines, and better-auth's error text, shared by every page script. */
13
+ const HELPERS = `const $=(id)=>document.getElementById(id);const status=$('status');const error=$('error');
14
+ const say=(message,isError)=>{status.textContent=isError?'':message;error.textContent=isError?message:'';};
15
+ const failed=async(response)=>{const text=await response.text();try{const body=JSON.parse(text);return body.message||body.error||text}catch{return text||'Request failed ('+response.status+')'}};`;
16
+ /** A value embedded in a page script as a JS string literal that cannot close the script element. */
17
+ const literal = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
18
+ /** Server-rendered, nonce-locked pages a signed-out or settings-only browser can load without the web bundle. */
19
+ var AuthWebPages = class {
20
+ routes;
21
+ nonce;
22
+ constructor(routes, nonce = randomNonce) {
23
+ this.routes = routes;
24
+ this.nonce = nonce;
25
+ }
26
+ /**
27
+ * Email and password with sign-up, magic link, and Google or GitHub only when the Worker has their credentials.
28
+ * `next` is where a signed-in browser goes; the gateway only passes its own invitation pages.
29
+ */
30
+ signIn(methods, next = "/") {
31
+ const { authBase } = this.routes;
32
+ const socialButtons = ["google", "github"].filter((provider) => methods[provider]).map((provider) => `<button type="button" class="secondary" data-provider="${provider}">Continue with ${provider === "google" ? "Google" : "GitHub"}</button>`).join("");
33
+ return this.#page("Sign in to Po", `<main><h1>Sign in to Po</h1>
34
+ ${socialButtons ? `<section>${socialButtons}</section>` : ""}
35
+ <form id="password-form"${methods.emailPassword ? "" : " hidden"}>
36
+ <label>Email<input id="email" type="email" autocomplete="email" required></label>
37
+ <label id="name-field" hidden>Name<input id="name" autocomplete="name"></label>
38
+ <label>Password<input id="password" type="password" autocomplete="current-password" minlength="8" required></label>
39
+ <button type="submit" id="password-submit">Sign in</button>
40
+ <button type="button" class="secondary" id="mode">Create an account</button></form>
41
+ <form id="link-form"${methods.magicLink ? "" : " hidden"}><p>Or get a sign-in link by email.</p>
42
+ <label>Email<input id="link-email" type="email" autocomplete="email" required></label>
43
+ <button type="submit" class="secondary">Email me a link</button></form>
44
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}let signUp=false;const next=${literal(next)};
45
+ const back='${this.routes.signIn}'+(next==='/'?'':'?next='+encodeURIComponent(next));
46
+ const post=(path,body)=>fetch('${authBase}'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
47
+ const params=new URLSearchParams(location.search);if(params.get('error'))say('That link did not work. It may have expired. Request a new one.',true);
48
+ if(params.get('verified'))say('Email confirmed. Sign in to continue.',false);
49
+ $('mode').addEventListener('click',()=>{signUp=!signUp;$('name-field').hidden=!signUp;
50
+ $('password').autocomplete=signUp?'new-password':'current-password';
51
+ $('password-submit').textContent=signUp?'Create account':'Sign in';$('mode').textContent=signUp?'I already have an account':'Create an account';say('',false);});
52
+ $('password-form').addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const email=$('email').value.trim();
53
+ if(signUp){const response=await post('/sign-up/email',{email,password:$('password').value,name:$('name').value.trim()||email.split('@')[0],callbackURL:back+(next==='/'?'?':'&')+'verified=1'});
54
+ if(!response.ok){say(await failed(response),true);return;}say('Check '+email+' for a link to confirm your email, then sign in.',false);return;}
55
+ const response=await post('/sign-in/email',{email,password:$('password').value});
56
+ if(response.status===403){say('Confirm your email first. We sent a new link to '+email+'.',true);return;}
57
+ if(!response.ok){say(await failed(response),true);return;}location.replace(next);});
58
+ $('link-form').addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const email=$('link-email').value.trim();
59
+ const response=await post('/sign-in/magic-link',{email,callbackURL:next,errorCallbackURL:back});
60
+ if(!response.ok){say(await failed(response),true);return;}say('Check '+email+' for a sign-in link. It expires in 5 minutes.',false);});
61
+ for(const button of document.querySelectorAll('[data-provider]'))button.addEventListener('click',async()=>{say('',false);
62
+ const response=await post('/sign-in/social',{provider:button.dataset.provider,callbackURL:next,errorCallbackURL:back});
63
+ const body=response.ok?await response.json():undefined;if(body&&body.url){location.assign(body.url);return;}say(response.ok?'Sign-in could not start.':await failed(response),true);});`);
64
+ }
65
+ /** Accept or decline one invitation. better-auth only shows it to the person it was sent to. */
66
+ invitation(id) {
67
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
68
+ return this.#page("Join a team on Po", `<main><h1>Join a team on Po</h1><p id="summary">Checking your invitation.</p>
69
+ <div class="row" id="actions" hidden><button type="button" id="accept">Accept</button><button type="button" class="secondary" id="decline">Decline</button></div>
70
+ <button type="button" class="secondary" id="switch" hidden>Sign in with a different email</button>
71
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}const id=${literal(id)};
72
+ const post=(path,body)=>fetch('${authBase}/organization/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
73
+ (async()=>{const response=await fetch('${authBase}/organization/get-invitation?id='+encodeURIComponent(id));
74
+ if(response.status===403){$('summary').textContent=await failed(response);$('switch').hidden=false;return;}
75
+ if(!response.ok){$('summary').textContent='This invitation has expired, was cancelled, or was already used.';return;}
76
+ const invite=await response.json();$('summary').textContent=invite.inviterEmail+' invited you to join '+invite.organizationName+' as '+invite.role+'.';$('actions').hidden=false;})();
77
+ $('accept').addEventListener('click',async()=>{say('',false);const response=await post('accept-invitation',{invitationId:id});
78
+ if(!response.ok){say(await failed(response),true);return;}location.replace('/');});
79
+ $('decline').addEventListener('click',async()=>{say('',false);const response=await post('reject-invitation',{invitationId:id});
80
+ if(!response.ok){say(await failed(response),true);return;}$('actions').hidden=true;$('summary').textContent='You declined the invitation.';});
81
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});
82
+ location.replace('${signIn}?next='+encodeURIComponent(location.pathname));});`);
83
+ }
84
+ /**
85
+ * A signed-in person's first team, or which of their teams this browser uses. Teams are better-auth organizations;
86
+ * the person names a new one and owns it. Afterwards the page goes on to `next`, a path on this site.
87
+ */
88
+ org(mode, orgs, next) {
89
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
90
+ const body = mode === "create" ? `<h1>Name your team</h1><p>Po keeps your sessions and settings in a team. You can invite people to it later.</p>
91
+ <form id="create-form"><label>Team name<input id="name" autocomplete="organization" maxlength="64" required></label>
92
+ <button type="submit">Create team</button></form>` : `<h1>Choose a team</h1><p>You belong to more than one team. Choose the one to use here. To change it later, sign out and sign in again.</p>
93
+ <ul id="orgs"></ul>`;
94
+ return this.#page(mode === "create" ? "Name your team" : "Choose a team", `<main>${body}
95
+ <button type="button" class="secondary" id="switch">Use a different account</button>
96
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}const next=${literal(next)};const orgs=JSON.parse(${literal(JSON.stringify(orgs))});
97
+ const post=(path,body)=>fetch('${authBase}/organization/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
98
+ const use=async(id)=>{const response=await post('set-active',{organizationId:id});if(!response.ok){say(await failed(response),true);return;}location.replace(next);};
99
+ const form=$('create-form');if(form)form.addEventListener('submit',async(event)=>{event.preventDefault();say('',false);const name=$('name').value.trim();if(!name)return;
100
+ const random=Array.from(crypto.getRandomValues(new Uint8Array(4)),(byte)=>byte.toString(16).padStart(2,'0')).join('');
101
+ const slug=(name.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'team')+'-'+random;
102
+ const response=await post('create',{name,slug});if(!response.ok){say(await failed(response),true);return;}await use((await response.json()).id);});
103
+ const list=$('orgs');if(list)list.replaceChildren(...orgs.map((entry)=>{const li=document.createElement('li');const text=document.createElement('div');text.textContent=entry.name;
104
+ const role=document.createElement('div');role.className='muted';role.textContent=entry.role;text.append(role);const button=document.createElement('button');button.type='button';
105
+ button.textContent='Use';button.addEventListener('click',()=>{say('',false);void use(entry.org);});li.append(text,button);return li;}));
106
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});location.replace('${signIn}');});`);
107
+ }
108
+ /**
109
+ * Allow or deny one Po Desktop sign-in. Claiming the code ties it to this person, so only they can answer it, and
110
+ * Desktop gets a session only after Allow. The code is shown so the person can check it matches Desktop's. A person
111
+ * in several teams chooses the one Desktop uses; Desktop never takes the browser's own team.
112
+ */
113
+ device(userCode, email, choice) {
114
+ const { authBase, ownerSession, csrfHeader, signIn } = this.routes;
115
+ return this.#page("Allow Po Desktop?", `<main><h1>Allow Po Desktop?</h1>
116
+ <p>Po Desktop wants to use your Po account <strong id="who"></strong>. Check that it shows this code.</p>
117
+ <label>Code<input id="code" autocomplete="off" spellcheck="false" maxlength="16"></label>
118
+ ${choice ? "<label>Team for Po Desktop<select id=\"org\"></select></label>" : ""}
119
+ <div class="row" id="actions"><button type="button" id="allow">Allow</button><button type="button" class="secondary" id="deny">Deny</button></div>
120
+ <button type="button" class="secondary" id="switch">Use a different account</button>
121
+ <p id="status" role="status"></p><p id="error" role="alert"></p></main>`, `${HELPERS}$('who').textContent=${literal(email)};const choice=JSON.parse(${literal(JSON.stringify(choice ?? null))});
122
+ if(choice)$('org').replaceChildren(...choice.orgs.map((entry)=>{const option=document.createElement('option');option.value=entry.org;option.textContent=entry.name;option.selected=entry.org===choice.active;return option;}));
123
+ const shown=(code)=>{const clean=code.replace(/[^A-Za-z0-9]/g,'').toUpperCase();return clean.length===8?clean.slice(0,4)+'-'+clean.slice(4):clean;};
124
+ $('code').value=shown(${literal(userCode)});
125
+ const post=(path)=>fetch('${authBase}/device/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({userCode:$('code').value})});
126
+ const answer=async(path,done)=>{say('',false);const claimed=await fetch('${authBase}/device?user_code='+encodeURIComponent($('code').value));
127
+ if(!claimed.ok){say('That code has expired or was already used. Start again from Po Desktop.',true);return;}
128
+ if(path==='approve'&&choice){const chosen=await fetch('${authBase}/device/organization',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({userCode:$('code').value,organizationId:$('org').value})});
129
+ if(!chosen.ok){say(await failed(chosen),true);return;}}
130
+ const response=await post(path);if(!response.ok){say(await failed(response),true);return;}$('actions').hidden=true;$('code').disabled=true;if(choice)$('org').disabled=true;say(done,false);};
131
+ $('allow').addEventListener('click',()=>void answer('approve','Po Desktop is signed in. You can close this tab.'));
132
+ $('deny').addEventListener('click',()=>void answer('deny','Denied. Po Desktop stays signed out. You can close this tab.'));
133
+ $('switch').addEventListener('click',async()=>{await fetch('${ownerSession}',{method:'DELETE',headers:{'${csrfHeader}':'1'}});
134
+ location.replace('${signIn}?next='+encodeURIComponent(location.pathname+'?user_code='+encodeURIComponent($('code').value)));});`);
135
+ }
136
+ #page(title, body, script) {
137
+ const nonce = this.nonce();
138
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
139
+ <meta name="robots" content="noindex, nofollow"><title>${title}</title><style nonce="${nonce}">${BASE_STYLE}</style></head>
140
+ <body>${body}<script nonce="${nonce}">${script}<\/script></body></html>`;
141
+ return new Response(html, { headers: {
142
+ "content-type": "text/html; charset=utf-8",
143
+ "cache-control": "no-store",
144
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'`,
145
+ "x-content-type-options": "nosniff",
146
+ "referrer-policy": "no-referrer"
147
+ } });
148
+ }
149
+ };
150
+ function randomNonce() {
151
+ return btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
152
+ }
153
+ //#endregion
154
+ export { AuthWebPages };
@@ -0,0 +1,22 @@
1
+ //#region src/services/authWebPages/type.d.ts
2
+ /** Routes the inline pages call. Pages stay under `/api/` so po-web's service worker never answers them. */
3
+ export interface AuthWebRoutes {
4
+ signIn: string;
5
+ ownerSession: string;
6
+ authBase: string;
7
+ csrfHeader: string;
8
+ }
9
+ /** One of the person's orgs, as the org and device pages list them. */
10
+ export interface AuthOrgChoice {
11
+ org: string;
12
+ name: string;
13
+ role: string;
14
+ }
15
+ /** Which sign-in methods the page shows. */
16
+ export interface AuthSignInMethods {
17
+ emailPassword: boolean;
18
+ magicLink: boolean;
19
+ google: boolean;
20
+ github: boolean;
21
+ }
22
+ //#endregion
@@ -1,4 +1,5 @@
1
1
  const require_index = require("../emailSender/index.cjs");
2
+ const require_index$1 = require("../identityWebRoutes/index.cjs");
2
3
  //#region src/services/identityConfiguration/index.ts
3
4
  function identityConfiguration(environment) {
4
5
  const required = (name) => {
@@ -30,6 +31,12 @@ function identityConfiguration(environment) {
30
31
  issuer: required("PO_IDENTITY_ISSUER"),
31
32
  jwtKeyWrap: required("PO_IDENTITY_JWT_KEY_WRAP"),
32
33
  socialProviders,
34
+ emailPassword: true,
35
+ deviceSignIn: {
36
+ verificationUri: new URL(require_index$1.IDENTITY_WEB_ROUTES.device, required("PO_IDENTITY_ISSUER")).href,
37
+ clientId: "po-desktop"
38
+ },
39
+ invitationUrl: new URL(require_index$1.IDENTITY_WEB_ROUTES.invitations, required("PO_IDENTITY_ISSUER")).href,
33
40
  ...environment.PO_IDENTITY_WEB_RP_ID ? { webPasskeys: {
34
41
  rpID: environment.PO_IDENTITY_WEB_RP_ID,
35
42
  origin: required("PO_IDENTITY_ISSUER")
@@ -27,6 +27,12 @@ export declare function identityConfiguration(environment: IdentityEnvironment):
27
27
  issuer: string;
28
28
  jwtKeyWrap: string;
29
29
  socialProviders: import("better-auth").SocialProviders;
30
+ emailPassword: true;
31
+ deviceSignIn: {
32
+ verificationUri: string;
33
+ clientId: string;
34
+ };
35
+ invitationUrl: string;
30
36
  webPasskeys?: {
31
37
  rpID: string;
32
38
  origin: string;
@@ -1,4 +1,5 @@
1
1
  import { unsendboxEmailSender } from "../emailSender/index.mjs";
2
+ import { IDENTITY_WEB_ROUTES } from "../identityWebRoutes/index.mjs";
2
3
  //#region src/services/identityConfiguration/index.ts
3
4
  function identityConfiguration(environment) {
4
5
  const required = (name) => {
@@ -30,6 +31,12 @@ function identityConfiguration(environment) {
30
31
  issuer: required("PO_IDENTITY_ISSUER"),
31
32
  jwtKeyWrap: required("PO_IDENTITY_JWT_KEY_WRAP"),
32
33
  socialProviders,
34
+ emailPassword: true,
35
+ deviceSignIn: {
36
+ verificationUri: new URL(IDENTITY_WEB_ROUTES.device, required("PO_IDENTITY_ISSUER")).href,
37
+ clientId: "po-desktop"
38
+ },
39
+ invitationUrl: new URL(IDENTITY_WEB_ROUTES.invitations, required("PO_IDENTITY_ISSUER")).href,
33
40
  ...environment.PO_IDENTITY_WEB_RP_ID ? { webPasskeys: {
34
41
  rpID: environment.PO_IDENTITY_WEB_RP_ID,
35
42
  origin: required("PO_IDENTITY_ISSUER")
@@ -0,0 +1,90 @@
1
+ let _agimon_ai_po_core = require("@agimon-ai/po-core");
2
+ //#region src/services/identityPairing/index.ts
3
+ const TTL_MS = 6e4;
4
+ const MAX_PROOFS = 1024;
5
+ const MAX_PER_PERSON = 8;
6
+ const MAX_BODY_BYTES = 2048;
7
+ const headers = { "cache-control": "no-store" };
8
+ const error = (status, message) => Response.json({ error: message }, {
9
+ status,
10
+ headers
11
+ });
12
+ /** Names a member for one pairing. Only the host's local approval can grant computer access. */
13
+ function createIdentityPairing(issuer, home, now = Date.now) {
14
+ const proofs = /* @__PURE__ */ new Map();
15
+ return {
16
+ async fetch(request) {
17
+ if (new URL(request.url).pathname !== _agimon_ai_po_core.AUTH_PAIRING_PROOF_PATH) return void 0;
18
+ if (request.method !== "POST") return error(405, "Use POST.");
19
+ const origin = request.headers.get("origin");
20
+ if (origin !== issuer && origin !== "po://" || request.headers.get("x-po-csrf") !== "1") return error(403, "Invalid origin.");
21
+ if (request.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/json") return error(400, "Use a JSON pairing request.");
22
+ const session = await home.signedIn(request.headers);
23
+ if (!session) return error(401, "Sign in before pairing.");
24
+ if (!session.org) return error(409, "Choose your team before pairing.");
25
+ const reader = request.body?.getReader();
26
+ if (!reader) return error(400, "A pairing request is required.");
27
+ let text = "";
28
+ let size = 0;
29
+ const decoder = new TextDecoder();
30
+ try {
31
+ for (;;) {
32
+ const chunk = await reader.read();
33
+ if (chunk.done) break;
34
+ size += chunk.value.byteLength;
35
+ if (size > MAX_BODY_BYTES) {
36
+ await reader.cancel();
37
+ return error(413, "The pairing request is too large.");
38
+ }
39
+ text += decoder.decode(chunk.value, { stream: true });
40
+ }
41
+ text += decoder.decode();
42
+ } catch {
43
+ return error(400, "The pairing request could not be read.");
44
+ } finally {
45
+ reader.releaseLock();
46
+ }
47
+ let body;
48
+ try {
49
+ body = JSON.parse(text);
50
+ } catch {
51
+ return error(400, "Use a JSON pairing request.");
52
+ }
53
+ if (!body || typeof body !== "object" || Array.isArray(body)) return error(400, "Invalid pairing request.");
54
+ const input = body;
55
+ if (Object.keys(input).length !== 2 || typeof input.requestId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/u.test(input.requestId) || typeof input.hostPublicKey !== "string" || !/^[A-Za-z0-9_-]{80,512}$/u.test(input.hostPublicKey)) return error(400, "Invalid pairing request.");
56
+ const at = now();
57
+ for (const [token, proof] of proofs) if (proof.expiresAt <= at) proofs.delete(token);
58
+ const subject = session.userId;
59
+ if (proofs.size >= MAX_PROOFS || [...proofs.values()].filter((p) => p.person.subject === subject).length >= MAX_PER_PERSON) return error(429, "Too many pending pairings. Try again in a minute.");
60
+ const proof = Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("");
61
+ const expiresAt = at + TTL_MS;
62
+ proofs.set(proof, {
63
+ requestId: input.requestId,
64
+ hostPublicKey: input.hostPublicKey,
65
+ person: {
66
+ issuer,
67
+ subject,
68
+ org: session.org
69
+ },
70
+ expiresAt
71
+ });
72
+ return Response.json({
73
+ proof,
74
+ expiresAt
75
+ }, { headers });
76
+ },
77
+ async consume(proof, request) {
78
+ const held = proofs.get(proof);
79
+ proofs.delete(proof);
80
+ if (!held || held.expiresAt <= now() || held.requestId !== request.requestId || held.hostPublicKey !== request.hostPublicKey) return void 0;
81
+ if (!await home.isOrgMember(held.person.subject, held.person.org)) return void 0;
82
+ return { ...held.person };
83
+ },
84
+ clear() {
85
+ proofs.clear();
86
+ }
87
+ };
88
+ }
89
+ //#endregion
90
+ exports.createIdentityPairing = createIdentityPairing;
@@ -0,0 +1,10 @@
1
+ import { createIdentityHome } from "../identityHome/index.mjs";
2
+ import { AuthPairingIdentity, AuthPairingRequest } from "@agimon-ai/po-core";
3
+ //#region src/services/identityPairing/index.d.ts
4
+ /** Names a member for one pairing. Only the host's local approval can grant computer access. */
5
+ export declare function createIdentityPairing(issuer: string, home: Pick<Awaited<ReturnType<typeof createIdentityHome>>, 'signedIn' | 'isOrgMember'>, now?: () => number): {
6
+ fetch(request: Request): Promise<Response | undefined>;
7
+ consume(proof: string, request: AuthPairingRequest): Promise<AuthPairingIdentity | undefined>;
8
+ clear(): void;
9
+ };
10
+ //#endregion
@@ -0,0 +1,90 @@
1
+ import { AUTH_PAIRING_PROOF_PATH } from "@agimon-ai/po-core";
2
+ //#region src/services/identityPairing/index.ts
3
+ const TTL_MS = 6e4;
4
+ const MAX_PROOFS = 1024;
5
+ const MAX_PER_PERSON = 8;
6
+ const MAX_BODY_BYTES = 2048;
7
+ const headers = { "cache-control": "no-store" };
8
+ const error = (status, message) => Response.json({ error: message }, {
9
+ status,
10
+ headers
11
+ });
12
+ /** Names a member for one pairing. Only the host's local approval can grant computer access. */
13
+ function createIdentityPairing(issuer, home, now = Date.now) {
14
+ const proofs = /* @__PURE__ */ new Map();
15
+ return {
16
+ async fetch(request) {
17
+ if (new URL(request.url).pathname !== AUTH_PAIRING_PROOF_PATH) return void 0;
18
+ if (request.method !== "POST") return error(405, "Use POST.");
19
+ const origin = request.headers.get("origin");
20
+ if (origin !== issuer && origin !== "po://" || request.headers.get("x-po-csrf") !== "1") return error(403, "Invalid origin.");
21
+ if (request.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/json") return error(400, "Use a JSON pairing request.");
22
+ const session = await home.signedIn(request.headers);
23
+ if (!session) return error(401, "Sign in before pairing.");
24
+ if (!session.org) return error(409, "Choose your team before pairing.");
25
+ const reader = request.body?.getReader();
26
+ if (!reader) return error(400, "A pairing request is required.");
27
+ let text = "";
28
+ let size = 0;
29
+ const decoder = new TextDecoder();
30
+ try {
31
+ for (;;) {
32
+ const chunk = await reader.read();
33
+ if (chunk.done) break;
34
+ size += chunk.value.byteLength;
35
+ if (size > MAX_BODY_BYTES) {
36
+ await reader.cancel();
37
+ return error(413, "The pairing request is too large.");
38
+ }
39
+ text += decoder.decode(chunk.value, { stream: true });
40
+ }
41
+ text += decoder.decode();
42
+ } catch {
43
+ return error(400, "The pairing request could not be read.");
44
+ } finally {
45
+ reader.releaseLock();
46
+ }
47
+ let body;
48
+ try {
49
+ body = JSON.parse(text);
50
+ } catch {
51
+ return error(400, "Use a JSON pairing request.");
52
+ }
53
+ if (!body || typeof body !== "object" || Array.isArray(body)) return error(400, "Invalid pairing request.");
54
+ const input = body;
55
+ if (Object.keys(input).length !== 2 || typeof input.requestId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/u.test(input.requestId) || typeof input.hostPublicKey !== "string" || !/^[A-Za-z0-9_-]{80,512}$/u.test(input.hostPublicKey)) return error(400, "Invalid pairing request.");
56
+ const at = now();
57
+ for (const [token, proof] of proofs) if (proof.expiresAt <= at) proofs.delete(token);
58
+ const subject = session.userId;
59
+ if (proofs.size >= MAX_PROOFS || [...proofs.values()].filter((p) => p.person.subject === subject).length >= MAX_PER_PERSON) return error(429, "Too many pending pairings. Try again in a minute.");
60
+ const proof = Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("");
61
+ const expiresAt = at + TTL_MS;
62
+ proofs.set(proof, {
63
+ requestId: input.requestId,
64
+ hostPublicKey: input.hostPublicKey,
65
+ person: {
66
+ issuer,
67
+ subject,
68
+ org: session.org
69
+ },
70
+ expiresAt
71
+ });
72
+ return Response.json({
73
+ proof,
74
+ expiresAt
75
+ }, { headers });
76
+ },
77
+ async consume(proof, request) {
78
+ const held = proofs.get(proof);
79
+ proofs.delete(proof);
80
+ if (!held || held.expiresAt <= now() || held.requestId !== request.requestId || held.hostPublicKey !== request.hostPublicKey) return void 0;
81
+ if (!await home.isOrgMember(held.person.subject, held.person.org)) return void 0;
82
+ return { ...held.person };
83
+ },
84
+ clear() {
85
+ proofs.clear();
86
+ }
87
+ };
88
+ }
89
+ //#endregion
90
+ export { createIdentityPairing };
@@ -0,0 +1,88 @@
1
+ const require_index = require("../authWebPages/index.cjs");
2
+ //#region src/services/identityWebRoutes/index.ts
3
+ /** Account pages, not a workspace bridge. A signed-in browser still pairs with the computer. */
4
+ const IDENTITY_WEB_ROUTES = {
5
+ signIn: "/api/auth/browser/sign-in",
6
+ ownerSession: "/api/auth/browser/session",
7
+ org: "/api/auth/browser/team",
8
+ device: "/api/auth/browser/device",
9
+ invitations: "/api/auth/browser/invitations/",
10
+ authBase: "/api/auth",
11
+ csrfHeader: "x-po-csrf"
12
+ };
13
+ const pages = new require_index.AuthWebPages(IDENTITY_WEB_ROUTES);
14
+ const invitation = /^\/api\/auth\/browser\/invitations\/([A-Za-z0-9_-]{1,128})$/u;
15
+ const device = /^\/api\/auth\/browser\/device(?:\?user_code=[A-Za-z0-9-]{1,16})?$/u;
16
+ const noStore = { "cache-control": "no-store" };
17
+ const redirect = (location) => new Response(null, {
18
+ status: 302,
19
+ headers: {
20
+ ...noStore,
21
+ location
22
+ }
23
+ });
24
+ /** Only these account pages and the pairing page can follow sign-in. Never a caller's URL. */
25
+ function nextPage(value, fallback) {
26
+ return value && (value === "/pair" || value === IDENTITY_WEB_ROUTES.org || invitation.test(value) || device.test(value)) ? value : fallback;
27
+ }
28
+ /** Node mounts these beside the same auth API Cloud uses. This function never admits a computer session. */
29
+ async function identityWebResponse(request, home) {
30
+ const url = new URL(request.url);
31
+ const path = url.pathname;
32
+ const invite = invitation.exec(path);
33
+ if (path !== IDENTITY_WEB_ROUTES.signIn && path !== IDENTITY_WEB_ROUTES.ownerSession && path !== IDENTITY_WEB_ROUTES.org && path !== IDENTITY_WEB_ROUTES.device && !invite) return void 0;
34
+ if (path === IDENTITY_WEB_ROUTES.ownerSession) {
35
+ if (request.method !== "DELETE") return new Response(null, {
36
+ status: 405,
37
+ headers: noStore
38
+ });
39
+ const { issuer } = await home.bootstrap(request.headers);
40
+ if (request.headers.get("origin") !== issuer || request.headers.get(IDENTITY_WEB_ROUTES.csrfHeader) !== "1") return new Response("Invalid origin", {
41
+ status: 403,
42
+ headers: noStore
43
+ });
44
+ const headers = new Headers(request.headers);
45
+ headers.set("content-type", "application/json");
46
+ return home.fetch(new Request(new URL("/api/auth/sign-out", request.url), {
47
+ method: "POST",
48
+ headers,
49
+ body: "{}"
50
+ }));
51
+ }
52
+ if (request.method !== "GET") return new Response(null, {
53
+ status: 405,
54
+ headers: noStore
55
+ });
56
+ if (path === IDENTITY_WEB_ROUTES.signIn) {
57
+ const { methods } = await home.bootstrap(request.headers);
58
+ return pages.signIn({
59
+ emailPassword: methods.emailPassword,
60
+ magicLink: methods.magicLink,
61
+ google: methods.providers.includes("google"),
62
+ github: methods.providers.includes("github")
63
+ }, nextPage(url.searchParams.get("next"), IDENTITY_WEB_ROUTES.org));
64
+ }
65
+ const code = url.searchParams.get("user_code") ?? "";
66
+ if (path === IDENTITY_WEB_ROUTES.device && code && !/^[A-Za-z0-9-]{1,16}$/u.test(code)) return new Response("Invalid device code", {
67
+ status: 400,
68
+ headers: noStore
69
+ });
70
+ const next = path === IDENTITY_WEB_ROUTES.device ? `${path}${code ? `?user_code=${encodeURIComponent(code)}` : ""}` : invite ? path : nextPage(url.searchParams.get("next"), "/pair");
71
+ const session = await home.signedIn(request.headers);
72
+ if (!session) {
73
+ const afterSignIn = path === IDENTITY_WEB_ROUTES.org ? IDENTITY_WEB_ROUTES.org : next;
74
+ return redirect(`${IDENTITY_WEB_ROUTES.signIn}?next=${encodeURIComponent(afterSignIn)}`);
75
+ }
76
+ if (invite) return pages.invitation(invite[1]);
77
+ if (path === IDENTITY_WEB_ROUTES.device) {
78
+ if (session.needsOrg === "create") return pages.org("create", session.orgs, next);
79
+ return pages.device(code, session.email, session.orgs.length > 1 ? {
80
+ orgs: session.orgs,
81
+ active: session.org
82
+ } : void 0);
83
+ }
84
+ return session.needsOrg ? pages.org(session.needsOrg, session.orgs, next) : redirect(next);
85
+ }
86
+ //#endregion
87
+ exports.IDENTITY_WEB_ROUTES = IDENTITY_WEB_ROUTES;
88
+ exports.identityWebResponse = identityWebResponse;
@@ -0,0 +1,87 @@
1
+ import { AuthWebPages } from "../authWebPages/index.mjs";
2
+ //#region src/services/identityWebRoutes/index.ts
3
+ /** Account pages, not a workspace bridge. A signed-in browser still pairs with the computer. */
4
+ const IDENTITY_WEB_ROUTES = {
5
+ signIn: "/api/auth/browser/sign-in",
6
+ ownerSession: "/api/auth/browser/session",
7
+ org: "/api/auth/browser/team",
8
+ device: "/api/auth/browser/device",
9
+ invitations: "/api/auth/browser/invitations/",
10
+ authBase: "/api/auth",
11
+ csrfHeader: "x-po-csrf"
12
+ };
13
+ const pages = new AuthWebPages(IDENTITY_WEB_ROUTES);
14
+ const invitation = /^\/api\/auth\/browser\/invitations\/([A-Za-z0-9_-]{1,128})$/u;
15
+ const device = /^\/api\/auth\/browser\/device(?:\?user_code=[A-Za-z0-9-]{1,16})?$/u;
16
+ const noStore = { "cache-control": "no-store" };
17
+ const redirect = (location) => new Response(null, {
18
+ status: 302,
19
+ headers: {
20
+ ...noStore,
21
+ location
22
+ }
23
+ });
24
+ /** Only these account pages and the pairing page can follow sign-in. Never a caller's URL. */
25
+ function nextPage(value, fallback) {
26
+ return value && (value === "/pair" || value === IDENTITY_WEB_ROUTES.org || invitation.test(value) || device.test(value)) ? value : fallback;
27
+ }
28
+ /** Node mounts these beside the same auth API Cloud uses. This function never admits a computer session. */
29
+ async function identityWebResponse(request, home) {
30
+ const url = new URL(request.url);
31
+ const path = url.pathname;
32
+ const invite = invitation.exec(path);
33
+ if (path !== IDENTITY_WEB_ROUTES.signIn && path !== IDENTITY_WEB_ROUTES.ownerSession && path !== IDENTITY_WEB_ROUTES.org && path !== IDENTITY_WEB_ROUTES.device && !invite) return void 0;
34
+ if (path === IDENTITY_WEB_ROUTES.ownerSession) {
35
+ if (request.method !== "DELETE") return new Response(null, {
36
+ status: 405,
37
+ headers: noStore
38
+ });
39
+ const { issuer } = await home.bootstrap(request.headers);
40
+ if (request.headers.get("origin") !== issuer || request.headers.get(IDENTITY_WEB_ROUTES.csrfHeader) !== "1") return new Response("Invalid origin", {
41
+ status: 403,
42
+ headers: noStore
43
+ });
44
+ const headers = new Headers(request.headers);
45
+ headers.set("content-type", "application/json");
46
+ return home.fetch(new Request(new URL("/api/auth/sign-out", request.url), {
47
+ method: "POST",
48
+ headers,
49
+ body: "{}"
50
+ }));
51
+ }
52
+ if (request.method !== "GET") return new Response(null, {
53
+ status: 405,
54
+ headers: noStore
55
+ });
56
+ if (path === IDENTITY_WEB_ROUTES.signIn) {
57
+ const { methods } = await home.bootstrap(request.headers);
58
+ return pages.signIn({
59
+ emailPassword: methods.emailPassword,
60
+ magicLink: methods.magicLink,
61
+ google: methods.providers.includes("google"),
62
+ github: methods.providers.includes("github")
63
+ }, nextPage(url.searchParams.get("next"), IDENTITY_WEB_ROUTES.org));
64
+ }
65
+ const code = url.searchParams.get("user_code") ?? "";
66
+ if (path === IDENTITY_WEB_ROUTES.device && code && !/^[A-Za-z0-9-]{1,16}$/u.test(code)) return new Response("Invalid device code", {
67
+ status: 400,
68
+ headers: noStore
69
+ });
70
+ const next = path === IDENTITY_WEB_ROUTES.device ? `${path}${code ? `?user_code=${encodeURIComponent(code)}` : ""}` : invite ? path : nextPage(url.searchParams.get("next"), "/pair");
71
+ const session = await home.signedIn(request.headers);
72
+ if (!session) {
73
+ const afterSignIn = path === IDENTITY_WEB_ROUTES.org ? IDENTITY_WEB_ROUTES.org : next;
74
+ return redirect(`${IDENTITY_WEB_ROUTES.signIn}?next=${encodeURIComponent(afterSignIn)}`);
75
+ }
76
+ if (invite) return pages.invitation(invite[1]);
77
+ if (path === IDENTITY_WEB_ROUTES.device) {
78
+ if (session.needsOrg === "create") return pages.org("create", session.orgs, next);
79
+ return pages.device(code, session.email, session.orgs.length > 1 ? {
80
+ orgs: session.orgs,
81
+ active: session.org
82
+ } : void 0);
83
+ }
84
+ return session.needsOrg ? pages.org(session.needsOrg, session.orgs, next) : redirect(next);
85
+ }
86
+ //#endregion
87
+ export { IDENTITY_WEB_ROUTES, identityWebResponse };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-auth-server",
3
- "version": "0.0.2-alpha.3",
3
+ "version": "0.0.2-alpha.5",
4
4
  "description": "Po auth server: sign-in, teams, device trust, recovery, rosters and delegated tokens for Node and Cloudflare hosts",
5
5
  "keywords": [
6
6
  "ai",
@@ -21,7 +21,7 @@
21
21
  "repository": {
22
22
  "type": "git",
23
23
  "url": "git+https://github.com/AgiFlow/po.git",
24
- "directory": "layers/identity/po-auth-server"
24
+ "directory": "layers/platform/po-auth-server"
25
25
  },
26
26
  "files": [
27
27
  "dist",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@agimon-ai/po-core": "0.0.0-alpha.161",
52
- "@agimon-ai/po-web-security": "0.0.0-alpha.161",
51
+ "@agimon-ai/po-core": "0.0.0-alpha.163",
52
+ "@agimon-ai/po-web-security": "0.0.0-alpha.163",
53
53
  "@better-auth/expo": "1.7.12",
54
54
  "@better-auth/passkey": "1.7.12",
55
55
  "@better-auth/sso": "1.7.12",
@@ -59,8 +59,8 @@
59
59
  "jose": "6.2.2"
60
60
  },
61
61
  "devDependencies": {
62
- "@agimon-ai/po-network": "0.0.2-alpha.108",
63
- "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.161",
62
+ "@agimon-ai/po-network": "0.0.2-alpha.110",
63
+ "@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.163",
64
64
  "@types/node": "26.4.1",
65
65
  "tsdown": "0.23.0",
66
66
  "typescript": "7.0.2",