@agimon-ai/po-auth-server 0.0.2-alpha.0 → 0.0.2-alpha.10

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.
@@ -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")
@@ -80,6 +80,22 @@ async function createIdentityHome(config, ports) {
80
80
  encryptOAuthTokens: true,
81
81
  accountLinking: { enabled: false }
82
82
  },
83
+ databaseHooks: { session: { create: { before: async (session, context) => {
84
+ if (session.activeOrganizationId || !context) return;
85
+ const teams = await context.context.adapter.findMany({
86
+ model: "member",
87
+ where: [{
88
+ field: "userId",
89
+ value: session.userId
90
+ }],
91
+ limit: 2
92
+ });
93
+ if (teams.length !== 1) return;
94
+ return { data: {
95
+ ...session,
96
+ activeOrganizationId: teams[0].organizationId
97
+ } };
98
+ } } } },
83
99
  ...config.emailPassword ? { emailAndPassword: {
84
100
  enabled: true,
85
101
  requireEmailVerification: true,
@@ -1116,7 +1132,8 @@ async function createIdentityHome(config, ports) {
1116
1132
  deviceSignIn: !!config.deviceSignIn,
1117
1133
  providers: Object.keys(socialProviders).filter((id) => socialProviders[id] !== void 0)
1118
1134
  },
1119
- session: await signedIn(headers)
1135
+ session: await signedIn(headers),
1136
+ cloud: config.cloud !== false
1120
1137
  };
1121
1138
  }
1122
1139
  async function fetchHandler(request) {
@@ -25,6 +25,8 @@ export interface IdentityHomeConfig {
25
25
  verificationUri: string;
26
26
  clientId: string;
27
27
  };
28
+ /** False on a host that signs people in but runs no Po Cloud, such as a Node server. The bootstrap says so. */
29
+ cloud?: boolean;
28
30
  /** The page an invitation email opens, followed by the invitation id. Absent mails the id itself. */
29
31
  invitationUrl?: string;
30
32
  /**
@@ -80,6 +80,22 @@ async function createIdentityHome(config, ports) {
80
80
  encryptOAuthTokens: true,
81
81
  accountLinking: { enabled: false }
82
82
  },
83
+ databaseHooks: { session: { create: { before: async (session, context) => {
84
+ if (session.activeOrganizationId || !context) return;
85
+ const teams = await context.context.adapter.findMany({
86
+ model: "member",
87
+ where: [{
88
+ field: "userId",
89
+ value: session.userId
90
+ }],
91
+ limit: 2
92
+ });
93
+ if (teams.length !== 1) return;
94
+ return { data: {
95
+ ...session,
96
+ activeOrganizationId: teams[0].organizationId
97
+ } };
98
+ } } } },
83
99
  ...config.emailPassword ? { emailAndPassword: {
84
100
  enabled: true,
85
101
  requireEmailVerification: true,
@@ -1116,7 +1132,8 @@ async function createIdentityHome(config, ports) {
1116
1132
  deviceSignIn: !!config.deviceSignIn,
1117
1133
  providers: Object.keys(socialProviders).filter((id) => socialProviders[id] !== void 0)
1118
1134
  },
1119
- session: await signedIn(headers)
1135
+ session: await signedIn(headers),
1136
+ cloud: config.cloud !== false
1120
1137
  };
1121
1138
  }
1122
1139
  async function fetchHandler(request) {
@@ -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;