@alien_org/sso-sdk-core 1.0.12 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var g=(a,s,t)=>new Promise((o,n)=>{var r=l=>{try{u(t.next(l))}catch(d){n(d)}},c=l=>{try{u(t.throw(l))}catch(d){n(d)}},u=l=>l.done?o(l.value):Promise.resolve(l.value).then(r,c);u((t=t.apply(a,s)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("zod/v4-mini"),$=require("js-sha256"),i=require("@solana/web3.js"),R=e.z.object({code_challenge:e.z.string(),code_challenge_method:e.z.literal("S256")}),_=e.z.object({deep_link:e.z.string(),polling_code:e.z.string(),expired_at:e.z.number()}),I=e.z.object({polling_code:e.z.string()}),Y=["pending","authorized","rejected","expired"],H=e.z.enum(Y),k=e.z.object({status:H,authorization_code:e.z.optional(e.z.string())}),E=e.z.object({authorization_code:e.z.string(),code_verifier:e.z.string()}),w=e.z.object({access_token:e.z.string()}),B=e.z.object({access_token:e.z.string()}),j=e.z.object({is_valid:e.z.boolean(),access_token:e.z.optional(e.z.string())}),T=e.z.object({app_callback_session_address:e.z.string(),expired_at:e.z.number(),issued_at:e.z.number()});function Q(a){return btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function P(a){let s=a.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4;)s+="=";return atob(s)}const Z="https://sso.alien.com",ee=5e3,f="alien-sso_",S=(a,s)=>new URL(s,a).toString(),v=e.z.object({ssoBaseUrl:e.z.url(),providerAddress:e.z.string(),pollingInterval:e.z.optional(e.z.number())});class se{constructor(s){this.config=v.parse(s),this.ssoBaseUrl=this.config.ssoBaseUrl||Z,this.providerAddress=this.config.providerAddress,this.pollingInterval=this.config.pollingInterval||ee}generateCodeVerifier(s=128){let t;const o=typeof window!="undefined"&&window.crypto;if(o&&o.getRandomValues)t=new Uint8Array(s),o.getRandomValues(t);else{t=new Uint8Array(s);for(let r=0;r<s;r++)t[r]=Math.floor(Math.random()*256)}let n="";for(let r=0;r<t.length;r++)n+=String.fromCharCode(t[r]);return Q(n)}generateCodeChallenge(s){return $.sha256(s)}generateDeeplink(){return g(this,null,function*(){const s=this.generateCodeVerifier(),t=this.generateCodeChallenge(s);sessionStorage.setItem(f+"code_verifier",s);const o=`${this.config.ssoBaseUrl}/sso/authorize`,n={code_challenge:t,code_challenge_method:"S256"};R.parse(n);const c=yield(yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(n)})).json();return _.parse(c)})}pollAuth(s){return g(this,null,function*(){const t={polling_code:s};I.parse(t);const o=yield fetch(S(this.config.ssoBaseUrl,"/sso/poll"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Poll failed: ${o.statusText}`);const n=yield o.json();return k.parse(n)})}exchangeToken(s){return g(this,null,function*(){const t=sessionStorage.getItem(f+"code_verifier");if(!t)throw new Error("Missing code verifier.");const o={authorization_code:s,code_verifier:t};E.parse(o);const n=yield fetch(S(this.config.ssoBaseUrl,"/sso/access_token/exchange"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(!n.ok)throw new Error(`ExchangeCode failed: ${n.statusText}`);const r=yield n.json(),c=w.parse(r);if(c.access_token)return localStorage.setItem(f+"access_token",c.access_token),c.access_token;throw new Error("Exchange failed")})}verifyAuth(){return g(this,null,function*(){const s=this.getAccessToken();if(!s)return!1;const t={access_token:s};B.parse(t);const o=yield fetch(S(this.config.ssoBaseUrl,"/sso/access_token/verify"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(!o.ok)return!1;const n=yield o.json(),r=j.parse(n);return r.access_token&&localStorage.setItem(f+"access_token",r.access_token),r.is_valid})}getAccessToken(){return localStorage.getItem(f+"access_token")}getAuthData(){const s=this.getAccessToken();if(!s)return null;const t=s.split(".");if(t.length!==3)return null;let o;try{const r=P(t[0]);o=JSON.parse(r)}catch(r){return null}if(o.alg!=="HS256"||o.typ!=="JWT")return null;let n;try{const r=JSON.parse(P(t[1]));n=T.parse(r)}catch(r){return null}return n}logout(){localStorage.removeItem(f+"access_token"),sessionStorage.removeItem(f+"code_verifier")}}const C=e.z.object({solana_address:e.z.string()}),D=e.z.object({deep_link:e.z.string(),polling_code:e.z.string(),expired_at:e.z.number()}),O=e.z.object({polling_code:e.z.string()}),te=["pending","authorized","rejected","expired"],oe=e.z.enum(te),U=e.z.object({status:oe,oracle_signature:e.z.optional(e.z.string()),oracle_public_key:e.z.optional(e.z.string()),solana_address:e.z.optional(e.z.string()),timestamp:e.z.optional(e.z.number()),session_address:e.z.optional(e.z.string())}),L=e.z.object({solana_address:e.z.string()}),x=e.z.object({session_address:e.z.string()});function ne(a){return i.PublicKey.findProgramAddressSync([Buffer.from("program_state")],a)}function re(a){return i.PublicKey.findProgramAddressSync([Buffer.from("credential_signer")],a)}function ae(a){return i.PublicKey.findProgramAddressSync([Buffer.from("session_registry")],a)}function ie(a,s){return i.PublicKey.findProgramAddressSync([Buffer.from("session"),Buffer.from(a)],s)}function ce(a,s){return i.PublicKey.findProgramAddressSync([Buffer.from("solana"),a.toBuffer()],s)}function le(a,s,t,o){return i.PublicKey.findProgramAddressSync([Buffer.from("attestation"),a.toBuffer(),s.toBuffer(),t.toBuffer()],o)}const de="https://sso.alien.com",ge=5e3,ue="9cstDz8WWRAFaq1vVpTjfHz6tjgh6SJaqYFeZWi1pFHG",fe="DeHa6pyZ2CFSbQQiNMm7FgoCXqmkX6tXG77C4Qycpta6",pe="22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",m=(a,s)=>new URL(s,a).toString(),V=e.z.object({ssoBaseUrl:e.z.url(),providerAddress:e.z.string(),pollingInterval:e.z.optional(e.z.number()),credentialSignerProgramId:e.z.optional(e.z.string()),sasProgramId:e.z.optional(e.z.string()),sessionRegistryProgramId:e.z.optional(e.z.string()),credentialAuthority:e.z.optional(e.z.string()),credentialName:e.z.optional(e.z.string()),schemaName:e.z.optional(e.z.string()),schemaVersion:e.z.optional(e.z.number())});class he{constructor(s){this.config=V.parse(s),this.ssoBaseUrl=this.config.ssoBaseUrl||de,this.providerAddress=this.config.providerAddress,this.pollingInterval=this.config.pollingInterval||ge,this.credentialSignerProgramId=new i.PublicKey(this.config.credentialSignerProgramId||ue),this.sasProgramId=new i.PublicKey(this.config.sasProgramId||pe),this.sessionRegistryProgramId=new i.PublicKey(this.config.sessionRegistryProgramId||fe)}generateDeeplink(s){return g(this,null,function*(){const t={solana_address:s};C.parse(t);const o=m(this.config.ssoBaseUrl,"/solana/link"),n=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(!n.ok)throw new Error(`GenerateLinkDeeplink failed: ${n.statusText}`);const r=yield n.json();return D.parse(r)})}pollAuth(s){return g(this,null,function*(){const t={polling_code:s};O.parse(t);const o=yield fetch(m(this.config.ssoBaseUrl,"/solana/poll"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Poll failed: ${o.statusText}`);const n=yield o.json();return U.parse(n)})}getAttestation(s){return g(this,null,function*(){const t={solana_address:s};L.parse(t);const o=yield fetch(m(this.config.ssoBaseUrl,"/solana/attestation"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(o.status===404)return null;if(!o.ok)throw new Error(`GetAttestation failed: ${o.statusText}`);const n=yield o.json();return x.parse(n).session_address})}buildCreateAttestationTransaction(s){return g(this,null,function*(){const{connection:t,payerPublicKey:o,sessionAddress:n,oracleSignature:r,oraclePublicKey:c,timestamp:u,expiry:l}=s,[d]=ne(this.credentialSignerProgramId),p=yield t.getAccountInfo(d);if(!p)throw new Error("ProgramState account not found");const y=p.data,z=new i.PublicKey(y.slice(40,72)),b=new i.PublicKey(y.slice(72,104)),[N]=re(this.credentialSignerProgramId),[q]=ae(this.sessionRegistryProgramId),[W]=ie(n,this.sessionRegistryProgramId),[K]=ce(o,this.sessionRegistryProgramId),[J]=le(z,b,o,this.sasProgramId),A=Buffer.alloc(8);A.writeBigInt64LE(BigInt(u));const G=Buffer.concat([Buffer.from(n),Buffer.from(o.toBase58()),A]),M=i.Ed25519Program.createInstructionWithPublicKey({publicKey:c.toBytes(),message:G,signature:r}),X=this.serializeCreateAttestationInstruction(n,Array.from(r),l,u),F=new i.TransactionInstruction({keys:[{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:N,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:z,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:J,isSigner:!1,isWritable:!0},{pubkey:i.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:this.sasProgramId,isSigner:!1,isWritable:!1},{pubkey:i.SYSVAR_INSTRUCTIONS_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:this.sessionRegistryProgramId,isSigner:!1,isWritable:!1},{pubkey:q,isSigner:!1,isWritable:!0},{pubkey:W,isSigner:!1,isWritable:!0},{pubkey:K,isSigner:!1,isWritable:!0}],programId:this.credentialSignerProgramId,data:X}),h=new i.Transaction;return h.add(M),h.add(F),h})}serializeCreateAttestationInstruction(s,t,o,n){const r=Buffer.from([49,24,67,80,12,249,96,239]),c=Buffer.alloc(4);c.writeUInt32LE(s.length);const u=Buffer.from(s),l=Buffer.from(t),d=Buffer.alloc(8);d.writeBigInt64LE(BigInt(o));const p=Buffer.alloc(8);return p.writeBigInt64LE(BigInt(n)),Buffer.concat([r,c,u,l,d,p])}}exports.AlienSolanaSsoClient=he;exports.AlienSolanaSsoClientSchema=V;exports.AlienSsoClient=se;exports.AlienSsoClientSchema=v;exports.AuthorizeRequestSchema=R;exports.AuthorizeResponseSchema=_;exports.ExchangeCodeRequestSchema=E;exports.ExchangeCodeResponseSchema=w;exports.PollRequestSchema=I;exports.PollResponseSchema=k;exports.SolanaAttestationRequestSchema=L;exports.SolanaAttestationResponseSchema=x;exports.SolanaLinkRequestSchema=C;exports.SolanaLinkResponseSchema=D;exports.SolanaPollRequestSchema=O;exports.SolanaPollResponseSchema=U;exports.TokenInfoSchema=T;exports.VerifyTokenRequestSchema=B;exports.VerifyTokenResponseSchema=j;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,214 @@
1
- export * from './client';
2
- export * from './errors';
3
- export * from './schema';
1
+ import { Connection } from '@solana/web3.js';
2
+ import { PublicKey } from '@solana/web3.js';
3
+ import { Transaction } from '@solana/web3.js';
4
+ import { z } from 'zod/v4-mini';
5
+
6
+ export declare class AlienSolanaSsoClient {
7
+ readonly config: AlienSolanaSsoClientConfig;
8
+ readonly pollingInterval: number;
9
+ readonly ssoBaseUrl: string;
10
+ readonly providerAddress: string;
11
+ readonly credentialSignerProgramId: PublicKey;
12
+ readonly sasProgramId: PublicKey;
13
+ readonly sessionRegistryProgramId: PublicKey;
14
+ constructor(config: AlienSolanaSsoClientConfig);
15
+ generateDeeplink(solanaAddress: string): Promise<SolanaLinkResponse>;
16
+ pollAuth(pollingCode: string): Promise<SolanaPollResponse>;
17
+ getAttestation(solanaAddress: string): Promise<string | null>;
18
+ buildCreateAttestationTransaction(params: {
19
+ connection: Connection;
20
+ payerPublicKey: PublicKey;
21
+ sessionAddress: string;
22
+ oracleSignature: Uint8Array;
23
+ oraclePublicKey: PublicKey;
24
+ timestamp: number;
25
+ expiry: number;
26
+ }): Promise<Transaction>;
27
+ private serializeCreateAttestationInstruction;
28
+ }
29
+
30
+ export declare type AlienSolanaSsoClientConfig = z.infer<typeof AlienSolanaSsoClientSchema>;
31
+
32
+ export declare const AlienSolanaSsoClientSchema: z.ZodMiniObject<{
33
+ ssoBaseUrl: z.ZodMiniURL;
34
+ providerAddress: z.ZodMiniString<string>;
35
+ pollingInterval: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
36
+ credentialSignerProgramId: z.ZodMiniOptional<z.ZodMiniString<string>>;
37
+ sasProgramId: z.ZodMiniOptional<z.ZodMiniString<string>>;
38
+ sessionRegistryProgramId: z.ZodMiniOptional<z.ZodMiniString<string>>;
39
+ credentialAuthority: z.ZodMiniOptional<z.ZodMiniString<string>>;
40
+ credentialName: z.ZodMiniOptional<z.ZodMiniString<string>>;
41
+ schemaName: z.ZodMiniOptional<z.ZodMiniString<string>>;
42
+ schemaVersion: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
43
+ }, z.core.$strip>;
44
+
45
+ export declare class AlienSsoClient {
46
+ readonly config: AlienSsoClientConfig;
47
+ readonly pollingInterval: number;
48
+ readonly ssoBaseUrl: string;
49
+ readonly providerAddress: string;
50
+ constructor(config: AlienSsoClientConfig);
51
+ private generateCodeVerifier;
52
+ private generateCodeChallenge;
53
+ generateDeeplink(): Promise<AuthorizeResponse>;
54
+ pollAuth(pollingCode: string): Promise<PollResponse>;
55
+ exchangeToken(authorizationCode: string): Promise<string>;
56
+ verifyAuth(): Promise<boolean>;
57
+ getAccessToken(): string | null;
58
+ getAuthData(): TokenInfo | null;
59
+ logout(): void;
60
+ }
61
+
62
+ export declare type AlienSsoClientConfig = z.infer<typeof AlienSsoClientSchema>;
63
+
64
+ export declare const AlienSsoClientSchema: z.ZodMiniObject<{
65
+ ssoBaseUrl: z.ZodMiniURL;
66
+ providerAddress: z.ZodMiniString<string>;
67
+ pollingInterval: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
68
+ }, z.core.$strip>;
69
+
70
+ export declare type AuthorizeRequest = z.infer<typeof AuthorizeRequestSchema>;
71
+
72
+ /**
73
+ * Authorize request/response schema
74
+ */
75
+ export declare const AuthorizeRequestSchema: z.ZodMiniObject<{
76
+ code_challenge: z.ZodMiniString<string>;
77
+ code_challenge_method: z.ZodMiniLiteral<"S256">;
78
+ }, z.core.$strip>;
79
+
80
+ export declare type AuthorizeResponse = z.infer<typeof AuthorizeResponseSchema>;
81
+
82
+ export declare const AuthorizeResponseSchema: z.ZodMiniObject<{
83
+ deep_link: z.ZodMiniString<string>;
84
+ polling_code: z.ZodMiniString<string>;
85
+ expired_at: z.ZodMiniNumber<number>;
86
+ }, z.core.$strip>;
87
+
88
+ export declare type ExchangeCodeRequest = z.infer<typeof ExchangeCodeRequestSchema>;
89
+
90
+ /**
91
+ * ExchangeCode request/response schema
92
+ */
93
+ export declare const ExchangeCodeRequestSchema: z.ZodMiniObject<{
94
+ authorization_code: z.ZodMiniString<string>;
95
+ code_verifier: z.ZodMiniString<string>;
96
+ }, z.core.$strip>;
97
+
98
+ export declare type ExchangeCodeResponse = z.infer<typeof ExchangeCodeResponseSchema>;
99
+
100
+ export declare const ExchangeCodeResponseSchema: z.ZodMiniObject<{
101
+ access_token: z.ZodMiniString<string>;
102
+ }, z.core.$strip>;
103
+
104
+ export declare interface JWTHeader {
105
+ alg: string;
106
+ typ: string;
107
+ }
108
+
109
+ export declare type PollRequest = z.infer<typeof PollRequestSchema>;
110
+
111
+ /**
112
+ * Poll request/response schema
113
+ */
114
+ export declare const PollRequestSchema: z.ZodMiniObject<{
115
+ polling_code: z.ZodMiniString<string>;
116
+ }, z.core.$strip>;
117
+
118
+ export declare type PollResponse = z.infer<typeof PollResponseSchema>;
119
+
120
+ export declare const PollResponseSchema: z.ZodMiniObject<{
121
+ status: z.ZodMiniEnum<{
122
+ pending: "pending";
123
+ authorized: "authorized";
124
+ rejected: "rejected";
125
+ expired: "expired";
126
+ }>;
127
+ authorization_code: z.ZodMiniOptional<z.ZodMiniString<string>>;
128
+ }, z.core.$strip>;
129
+
130
+ export declare type SolanaAttestationRequest = z.infer<typeof SolanaAttestationRequestSchema>;
131
+
132
+ /**
133
+ * Solana Attestation request/response schema
134
+ */
135
+ export declare const SolanaAttestationRequestSchema: z.ZodMiniObject<{
136
+ solana_address: z.ZodMiniString<string>;
137
+ }, z.core.$strip>;
138
+
139
+ export declare type SolanaAttestationResponse = z.infer<typeof SolanaAttestationResponseSchema>;
140
+
141
+ export declare const SolanaAttestationResponseSchema: z.ZodMiniObject<{
142
+ session_address: z.ZodMiniString<string>;
143
+ }, z.core.$strip>;
144
+
145
+ export declare type SolanaLinkRequest = z.infer<typeof SolanaLinkRequestSchema>;
146
+
147
+ /**
148
+ * Solana Link request/response schema
149
+ */
150
+ export declare const SolanaLinkRequestSchema: z.ZodMiniObject<{
151
+ solana_address: z.ZodMiniString<string>;
152
+ }, z.core.$strip>;
153
+
154
+ export declare type SolanaLinkResponse = z.infer<typeof SolanaLinkResponseSchema>;
155
+
156
+ export declare const SolanaLinkResponseSchema: z.ZodMiniObject<{
157
+ deep_link: z.ZodMiniString<string>;
158
+ polling_code: z.ZodMiniString<string>;
159
+ expired_at: z.ZodMiniNumber<number>;
160
+ }, z.core.$strip>;
161
+
162
+ export declare type SolanaPollRequest = z.infer<typeof SolanaPollRequestSchema>;
163
+
164
+ /**
165
+ * Solana Poll request/response schema
166
+ */
167
+ export declare const SolanaPollRequestSchema: z.ZodMiniObject<{
168
+ polling_code: z.ZodMiniString<string>;
169
+ }, z.core.$strip>;
170
+
171
+ export declare type SolanaPollResponse = z.infer<typeof SolanaPollResponseSchema>;
172
+
173
+ export declare const SolanaPollResponseSchema: z.ZodMiniObject<{
174
+ status: z.ZodMiniEnum<{
175
+ pending: "pending";
176
+ authorized: "authorized";
177
+ rejected: "rejected";
178
+ expired: "expired";
179
+ }>;
180
+ oracle_signature: z.ZodMiniOptional<z.ZodMiniString<string>>;
181
+ oracle_public_key: z.ZodMiniOptional<z.ZodMiniString<string>>;
182
+ solana_address: z.ZodMiniOptional<z.ZodMiniString<string>>;
183
+ timestamp: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
184
+ session_address: z.ZodMiniOptional<z.ZodMiniString<string>>;
185
+ }, z.core.$strip>;
186
+
187
+ export declare type TokenInfo = z.infer<typeof TokenInfoSchema>;
188
+
189
+ /**
190
+ * Token info schema
191
+ */
192
+ export declare const TokenInfoSchema: z.ZodMiniObject<{
193
+ app_callback_session_address: z.ZodMiniString<string>;
194
+ expired_at: z.ZodMiniNumber<number>;
195
+ issued_at: z.ZodMiniNumber<number>;
196
+ }, z.core.$strip>;
197
+
198
+ export declare type VerifyTokenRequest = z.infer<typeof VerifyTokenRequestSchema>;
199
+
200
+ /**
201
+ * VerifyToken request/response schema
202
+ */
203
+ export declare const VerifyTokenRequestSchema: z.ZodMiniObject<{
204
+ access_token: z.ZodMiniString<string>;
205
+ }, z.core.$strip>;
206
+
207
+ export declare type VerifyTokenResponse = z.infer<typeof VerifyTokenResponseSchema>;
208
+
209
+ export declare const VerifyTokenResponseSchema: z.ZodMiniObject<{
210
+ is_valid: z.ZodMiniBoolean<boolean>;
211
+ access_token: z.ZodMiniOptional<z.ZodMiniString<string>>;
212
+ }, z.core.$strip>;
213
+
214
+ export { }
@@ -0,0 +1,465 @@
1
+ var g = (a, s, t) => new Promise((o, n) => {
2
+ var r = (c) => {
3
+ try {
4
+ f(t.next(c));
5
+ } catch (d) {
6
+ n(d);
7
+ }
8
+ }, i = (c) => {
9
+ try {
10
+ f(t.throw(c));
11
+ } catch (d) {
12
+ n(d);
13
+ }
14
+ }, f = (c) => c.done ? o(c.value) : Promise.resolve(c.value).then(r, i);
15
+ f((t = t.apply(a, s)).next());
16
+ });
17
+ import { z as e } from "zod/v4-mini";
18
+ import { sha256 as D } from "js-sha256";
19
+ import { PublicKey as l, Ed25519Program as C, TransactionInstruction as O, SystemProgram as U, SYSVAR_INSTRUCTIONS_PUBKEY as L, Transaction as x } from "@solana/web3.js";
20
+ const N = e.object({
21
+ code_challenge: e.string(),
22
+ code_challenge_method: e.literal("S256")
23
+ }), V = e.object({
24
+ deep_link: e.string(),
25
+ polling_code: e.string(),
26
+ expired_at: e.number()
27
+ }), W = e.object({
28
+ polling_code: e.string()
29
+ }), z = ["pending", "authorized", "rejected", "expired"], J = e.enum(z), G = e.object({
30
+ status: J,
31
+ authorization_code: e.optional(e.string())
32
+ }), q = e.object({
33
+ authorization_code: e.string(),
34
+ code_verifier: e.string()
35
+ }), X = e.object({
36
+ access_token: e.string()
37
+ }), F = e.object({
38
+ access_token: e.string()
39
+ }), M = e.object({
40
+ is_valid: e.boolean(),
41
+ access_token: e.optional(e.string())
42
+ }), $ = e.object({
43
+ app_callback_session_address: e.string(),
44
+ expired_at: e.number(),
45
+ issued_at: e.number()
46
+ });
47
+ function K(a) {
48
+ return btoa(a).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
49
+ }
50
+ function P(a) {
51
+ let s = a.replace(/-/g, "+").replace(/_/g, "/");
52
+ for (; s.length % 4; )
53
+ s += "=";
54
+ return atob(s);
55
+ }
56
+ const Y = "https://sso.alien.com", H = 5e3, p = "alien-sso_", S = (a, s) => new URL(s, a).toString(), Q = e.object({
57
+ ssoBaseUrl: e.url(),
58
+ providerAddress: e.string(),
59
+ pollingInterval: e.optional(e.number())
60
+ });
61
+ class Re {
62
+ constructor(s) {
63
+ this.config = Q.parse(s), this.ssoBaseUrl = this.config.ssoBaseUrl || Y, this.providerAddress = this.config.providerAddress, this.pollingInterval = this.config.pollingInterval || H;
64
+ }
65
+ generateCodeVerifier(s = 128) {
66
+ let t;
67
+ const o = typeof window != "undefined" && window.crypto;
68
+ if (o && o.getRandomValues)
69
+ t = new Uint8Array(s), o.getRandomValues(t);
70
+ else {
71
+ t = new Uint8Array(s);
72
+ for (let r = 0; r < s; r++)
73
+ t[r] = Math.floor(Math.random() * 256);
74
+ }
75
+ let n = "";
76
+ for (let r = 0; r < t.length; r++)
77
+ n += String.fromCharCode(t[r]);
78
+ return K(n);
79
+ }
80
+ generateCodeChallenge(s) {
81
+ return D(s);
82
+ }
83
+ generateDeeplink() {
84
+ return g(this, null, function* () {
85
+ const s = this.generateCodeVerifier(), t = this.generateCodeChallenge(s);
86
+ sessionStorage.setItem(p + "code_verifier", s);
87
+ const o = `${this.config.ssoBaseUrl}/sso/authorize`, n = {
88
+ code_challenge: t,
89
+ code_challenge_method: "S256"
90
+ };
91
+ N.parse(n);
92
+ const i = yield (yield fetch(o, {
93
+ method: "POST",
94
+ headers: {
95
+ "Content-Type": "application/json",
96
+ "X-PROVIDER-ADDRESS": this.providerAddress
97
+ },
98
+ body: JSON.stringify(n)
99
+ })).json();
100
+ return V.parse(i);
101
+ });
102
+ }
103
+ pollAuth(s) {
104
+ return g(this, null, function* () {
105
+ const t = {
106
+ polling_code: s
107
+ };
108
+ W.parse(t);
109
+ const o = yield fetch(S(this.config.ssoBaseUrl, "/sso/poll"), {
110
+ method: "POST",
111
+ headers: {
112
+ "Content-Type": "application/json",
113
+ "X-PROVIDER-ADDRESS": this.providerAddress
114
+ },
115
+ body: JSON.stringify(t)
116
+ });
117
+ if (!o.ok)
118
+ throw new Error(`Poll failed: ${o.statusText}`);
119
+ const n = yield o.json();
120
+ return G.parse(n);
121
+ });
122
+ }
123
+ exchangeToken(s) {
124
+ return g(this, null, function* () {
125
+ const t = sessionStorage.getItem(p + "code_verifier");
126
+ if (!t) throw new Error("Missing code verifier.");
127
+ const o = {
128
+ authorization_code: s,
129
+ code_verifier: t
130
+ };
131
+ q.parse(o);
132
+ const n = yield fetch(
133
+ S(this.config.ssoBaseUrl, "/sso/access_token/exchange"),
134
+ {
135
+ method: "POST",
136
+ headers: {
137
+ "Content-Type": "application/json",
138
+ "X-PROVIDER-ADDRESS": this.providerAddress
139
+ },
140
+ body: JSON.stringify(o)
141
+ }
142
+ );
143
+ if (!n.ok)
144
+ throw new Error(`ExchangeCode failed: ${n.statusText}`);
145
+ const r = yield n.json(), i = X.parse(r);
146
+ if (i.access_token)
147
+ return localStorage.setItem(
148
+ p + "access_token",
149
+ i.access_token
150
+ ), i.access_token;
151
+ throw new Error("Exchange failed");
152
+ });
153
+ }
154
+ verifyAuth() {
155
+ return g(this, null, function* () {
156
+ const s = this.getAccessToken();
157
+ if (!s)
158
+ return !1;
159
+ const t = {
160
+ access_token: s
161
+ };
162
+ F.parse(t);
163
+ const o = yield fetch(
164
+ S(this.config.ssoBaseUrl, "/sso/access_token/verify"),
165
+ {
166
+ method: "POST",
167
+ headers: {
168
+ "Content-Type": "application/json",
169
+ "X-PROVIDER-ADDRESS": this.providerAddress
170
+ },
171
+ body: JSON.stringify(t)
172
+ }
173
+ );
174
+ if (!o.ok)
175
+ return !1;
176
+ const n = yield o.json(), r = M.parse(n);
177
+ return r.access_token && localStorage.setItem(
178
+ p + "access_token",
179
+ r.access_token
180
+ ), r.is_valid;
181
+ });
182
+ }
183
+ getAccessToken() {
184
+ return localStorage.getItem(p + "access_token");
185
+ }
186
+ getAuthData() {
187
+ const s = this.getAccessToken();
188
+ if (!s) return null;
189
+ const t = s.split(".");
190
+ if (t.length !== 3)
191
+ return null;
192
+ let o;
193
+ try {
194
+ const r = P(t[0]);
195
+ o = JSON.parse(r);
196
+ } catch (r) {
197
+ return null;
198
+ }
199
+ if (o.alg !== "HS256" || o.typ !== "JWT")
200
+ return null;
201
+ let n;
202
+ try {
203
+ const r = JSON.parse(P(t[1]));
204
+ n = $.parse(r);
205
+ } catch (r) {
206
+ return null;
207
+ }
208
+ return n;
209
+ }
210
+ logout() {
211
+ localStorage.removeItem(p + "access_token"), sessionStorage.removeItem(p + "code_verifier");
212
+ }
213
+ }
214
+ const Z = e.object({
215
+ solana_address: e.string()
216
+ }), ee = e.object({
217
+ deep_link: e.string(),
218
+ polling_code: e.string(),
219
+ expired_at: e.number()
220
+ }), se = e.object({
221
+ polling_code: e.string()
222
+ }), te = ["pending", "authorized", "rejected", "expired"], oe = e.enum(te), ne = e.object({
223
+ status: oe,
224
+ oracle_signature: e.optional(e.string()),
225
+ oracle_public_key: e.optional(e.string()),
226
+ solana_address: e.optional(e.string()),
227
+ timestamp: e.optional(e.number()),
228
+ session_address: e.optional(e.string())
229
+ }), re = e.object({
230
+ solana_address: e.string()
231
+ }), ae = e.object({
232
+ session_address: e.string()
233
+ });
234
+ function ie(a) {
235
+ return l.findProgramAddressSync(
236
+ [Buffer.from("program_state")],
237
+ a
238
+ );
239
+ }
240
+ function ce(a) {
241
+ return l.findProgramAddressSync(
242
+ [Buffer.from("credential_signer")],
243
+ a
244
+ );
245
+ }
246
+ function le(a) {
247
+ return l.findProgramAddressSync(
248
+ [Buffer.from("session_registry")],
249
+ a
250
+ );
251
+ }
252
+ function de(a, s) {
253
+ return l.findProgramAddressSync(
254
+ [Buffer.from("session"), Buffer.from(a)],
255
+ s
256
+ );
257
+ }
258
+ function ge(a, s) {
259
+ return l.findProgramAddressSync(
260
+ [Buffer.from("solana"), a.toBuffer()],
261
+ s
262
+ );
263
+ }
264
+ function fe(a, s, t, o) {
265
+ return l.findProgramAddressSync(
266
+ [
267
+ Buffer.from("attestation"),
268
+ a.toBuffer(),
269
+ s.toBuffer(),
270
+ t.toBuffer()
271
+ ],
272
+ o
273
+ );
274
+ }
275
+ const pe = "https://sso.alien.com", ue = 5e3, he = "9cstDz8WWRAFaq1vVpTjfHz6tjgh6SJaqYFeZWi1pFHG", Se = "DeHa6pyZ2CFSbQQiNMm7FgoCXqmkX6tXG77C4Qycpta6", me = "22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG", m = (a, s) => new URL(s, a).toString(), ye = e.object({
276
+ ssoBaseUrl: e.url(),
277
+ providerAddress: e.string(),
278
+ pollingInterval: e.optional(e.number()),
279
+ credentialSignerProgramId: e.optional(e.string()),
280
+ sasProgramId: e.optional(e.string()),
281
+ sessionRegistryProgramId: e.optional(e.string()),
282
+ credentialAuthority: e.optional(e.string()),
283
+ credentialName: e.optional(e.string()),
284
+ schemaName: e.optional(e.string()),
285
+ schemaVersion: e.optional(e.number())
286
+ });
287
+ class Ie {
288
+ constructor(s) {
289
+ this.config = ye.parse(s), this.ssoBaseUrl = this.config.ssoBaseUrl || pe, this.providerAddress = this.config.providerAddress, this.pollingInterval = this.config.pollingInterval || ue, this.credentialSignerProgramId = new l(
290
+ this.config.credentialSignerProgramId || he
291
+ ), this.sasProgramId = new l(
292
+ this.config.sasProgramId || me
293
+ ), this.sessionRegistryProgramId = new l(
294
+ this.config.sessionRegistryProgramId || Se
295
+ );
296
+ }
297
+ generateDeeplink(s) {
298
+ return g(this, null, function* () {
299
+ const t = {
300
+ solana_address: s
301
+ };
302
+ Z.parse(t);
303
+ const o = m(this.config.ssoBaseUrl, "/solana/link"), n = yield fetch(o, {
304
+ method: "POST",
305
+ headers: {
306
+ "Content-Type": "application/json",
307
+ "X-PROVIDER-ADDRESS": this.providerAddress
308
+ },
309
+ body: JSON.stringify(t)
310
+ });
311
+ if (!n.ok)
312
+ throw new Error(`GenerateLinkDeeplink failed: ${n.statusText}`);
313
+ const r = yield n.json();
314
+ return ee.parse(r);
315
+ });
316
+ }
317
+ pollAuth(s) {
318
+ return g(this, null, function* () {
319
+ const t = {
320
+ polling_code: s
321
+ };
322
+ se.parse(t);
323
+ const o = yield fetch(
324
+ m(this.config.ssoBaseUrl, "/solana/poll"),
325
+ {
326
+ method: "POST",
327
+ headers: {
328
+ "Content-Type": "application/json",
329
+ "X-PROVIDER-ADDRESS": this.providerAddress
330
+ },
331
+ body: JSON.stringify(t)
332
+ }
333
+ );
334
+ if (!o.ok)
335
+ throw new Error(`Poll failed: ${o.statusText}`);
336
+ const n = yield o.json();
337
+ return ne.parse(n);
338
+ });
339
+ }
340
+ getAttestation(s) {
341
+ return g(this, null, function* () {
342
+ const t = {
343
+ solana_address: s
344
+ };
345
+ re.parse(t);
346
+ const o = yield fetch(
347
+ m(this.config.ssoBaseUrl, "/solana/attestation"),
348
+ {
349
+ method: "POST",
350
+ headers: {
351
+ "Content-Type": "application/json",
352
+ "X-PROVIDER-ADDRESS": this.providerAddress
353
+ },
354
+ body: JSON.stringify(t)
355
+ }
356
+ );
357
+ if (o.status === 404)
358
+ return null;
359
+ if (!o.ok)
360
+ throw new Error(`GetAttestation failed: ${o.statusText}`);
361
+ const n = yield o.json();
362
+ return ae.parse(n).session_address;
363
+ });
364
+ }
365
+ buildCreateAttestationTransaction(s) {
366
+ return g(this, null, function* () {
367
+ const {
368
+ connection: t,
369
+ payerPublicKey: o,
370
+ sessionAddress: n,
371
+ oracleSignature: r,
372
+ oraclePublicKey: i,
373
+ timestamp: f,
374
+ expiry: c
375
+ } = s, [d] = ie(this.credentialSignerProgramId), u = yield t.getAccountInfo(d);
376
+ if (!u)
377
+ throw new Error("ProgramState account not found");
378
+ const y = u.data, _ = new l(y.slice(40, 72)), A = new l(y.slice(72, 104)), [R] = ce(this.credentialSignerProgramId), [I] = le(this.sessionRegistryProgramId), [k] = de(n, this.sessionRegistryProgramId), [w] = ge(o, this.sessionRegistryProgramId), [B] = fe(
379
+ _,
380
+ A,
381
+ o,
382
+ this.sasProgramId
383
+ ), b = Buffer.alloc(8);
384
+ b.writeBigInt64LE(BigInt(f));
385
+ const E = Buffer.concat([
386
+ Buffer.from(n),
387
+ Buffer.from(o.toBase58()),
388
+ b
389
+ ]), j = C.createInstructionWithPublicKey({
390
+ publicKey: i.toBytes(),
391
+ message: E,
392
+ signature: r
393
+ }), T = this.serializeCreateAttestationInstruction(
394
+ n,
395
+ Array.from(r),
396
+ c,
397
+ f
398
+ ), v = new O({
399
+ keys: [
400
+ { pubkey: d, isSigner: !1, isWritable: !1 },
401
+ { pubkey: R, isSigner: !1, isWritable: !1 },
402
+ { pubkey: o, isSigner: !0, isWritable: !0 },
403
+ { pubkey: _, isSigner: !1, isWritable: !1 },
404
+ { pubkey: A, isSigner: !1, isWritable: !1 },
405
+ { pubkey: B, isSigner: !1, isWritable: !0 },
406
+ { pubkey: U.programId, isSigner: !1, isWritable: !1 },
407
+ { pubkey: this.sasProgramId, isSigner: !1, isWritable: !1 },
408
+ { pubkey: L, isSigner: !1, isWritable: !1 },
409
+ { pubkey: this.sessionRegistryProgramId, isSigner: !1, isWritable: !1 },
410
+ { pubkey: I, isSigner: !1, isWritable: !0 },
411
+ { pubkey: k, isSigner: !1, isWritable: !0 },
412
+ { pubkey: w, isSigner: !1, isWritable: !0 }
413
+ ],
414
+ programId: this.credentialSignerProgramId,
415
+ data: T
416
+ }), h = new x();
417
+ return h.add(j), h.add(v), h;
418
+ });
419
+ }
420
+ serializeCreateAttestationInstruction(s, t, o, n) {
421
+ const r = Buffer.from([
422
+ 49,
423
+ 24,
424
+ 67,
425
+ 80,
426
+ 12,
427
+ 249,
428
+ 96,
429
+ 239
430
+ ]), i = Buffer.alloc(4);
431
+ i.writeUInt32LE(s.length);
432
+ const f = Buffer.from(s), c = Buffer.from(t), d = Buffer.alloc(8);
433
+ d.writeBigInt64LE(BigInt(o));
434
+ const u = Buffer.alloc(8);
435
+ return u.writeBigInt64LE(BigInt(n)), Buffer.concat([
436
+ r,
437
+ i,
438
+ f,
439
+ c,
440
+ d,
441
+ u
442
+ ]);
443
+ }
444
+ }
445
+ export {
446
+ Ie as AlienSolanaSsoClient,
447
+ ye as AlienSolanaSsoClientSchema,
448
+ Re as AlienSsoClient,
449
+ Q as AlienSsoClientSchema,
450
+ N as AuthorizeRequestSchema,
451
+ V as AuthorizeResponseSchema,
452
+ q as ExchangeCodeRequestSchema,
453
+ X as ExchangeCodeResponseSchema,
454
+ W as PollRequestSchema,
455
+ G as PollResponseSchema,
456
+ re as SolanaAttestationRequestSchema,
457
+ ae as SolanaAttestationResponseSchema,
458
+ Z as SolanaLinkRequestSchema,
459
+ ee as SolanaLinkResponseSchema,
460
+ se as SolanaPollRequestSchema,
461
+ ne as SolanaPollResponseSchema,
462
+ $ as TokenInfoSchema,
463
+ F as VerifyTokenRequestSchema,
464
+ M as VerifyTokenResponseSchema
465
+ };
@@ -0,0 +1 @@
1
+ (function(n,e){typeof exports=="object"&&typeof module!="undefined"?e(exports,require("zod/v4-mini"),require("js-sha256"),require("@solana/web3.js")):typeof define=="function"&&define.amd?define(["exports","zod/v4-mini","js-sha256","@solana/web3.js"],e):(n=typeof globalThis!="undefined"?globalThis:n||self,e(n.AlienSsoCore={},n.Zod,n.jsSha256,n.solanaWeb3))})(this,(function(n,e,f,c){"use strict";var g=(n,e,f)=>new Promise((c,S)=>{var z=d=>{try{p(f.next(d))}catch(h){S(h)}},A=d=>{try{p(f.throw(d))}catch(h){S(h)}},p=d=>d.done?c(d.value):Promise.resolve(d.value).then(z,A);p((f=f.apply(n,e)).next())});const S=e.z.object({code_challenge:e.z.string(),code_challenge_method:e.z.literal("S256")}),z=e.z.object({deep_link:e.z.string(),polling_code:e.z.string(),expired_at:e.z.number()}),A=e.z.object({polling_code:e.z.string()}),p=["pending","authorized","rejected","expired"],d=e.z.enum(p),h=e.z.object({status:d,authorization_code:e.z.optional(e.z.string())}),k=e.z.object({authorization_code:e.z.string(),code_verifier:e.z.string()}),E=e.z.object({access_token:e.z.string()}),B=e.z.object({access_token:e.z.string()}),T=e.z.object({is_valid:e.z.boolean(),access_token:e.z.optional(e.z.string())}),C=e.z.object({app_callback_session_address:e.z.string(),expired_at:e.z.number(),issued_at:e.z.number()});function X(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function w(i){let s=i.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4;)s+="=";return atob(s)}const F="https://sso.alien.com",$=5e3,u="alien-sso_",R=(i,s)=>new URL(s,i).toString(),j=e.z.object({ssoBaseUrl:e.z.url(),providerAddress:e.z.string(),pollingInterval:e.z.optional(e.z.number())});class x{constructor(s){this.config=j.parse(s),this.ssoBaseUrl=this.config.ssoBaseUrl||F,this.providerAddress=this.config.providerAddress,this.pollingInterval=this.config.pollingInterval||$}generateCodeVerifier(s=128){let o;const t=typeof window!="undefined"&&window.crypto;if(t&&t.getRandomValues)o=new Uint8Array(s),t.getRandomValues(o);else{o=new Uint8Array(s);for(let a=0;a<s;a++)o[a]=Math.floor(Math.random()*256)}let r="";for(let a=0;a<o.length;a++)r+=String.fromCharCode(o[a]);return X(r)}generateCodeChallenge(s){return f.sha256(s)}generateDeeplink(){return g(this,null,function*(){const s=this.generateCodeVerifier(),o=this.generateCodeChallenge(s);sessionStorage.setItem(u+"code_verifier",s);const t=`${this.config.ssoBaseUrl}/sso/authorize`,r={code_challenge:o,code_challenge_method:"S256"};S.parse(r);const l=yield(yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(r)})).json();return z.parse(l)})}pollAuth(s){return g(this,null,function*(){const o={polling_code:s};A.parse(o);const t=yield fetch(R(this.config.ssoBaseUrl,"/sso/poll"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(!t.ok)throw new Error(`Poll failed: ${t.statusText}`);const r=yield t.json();return h.parse(r)})}exchangeToken(s){return g(this,null,function*(){const o=sessionStorage.getItem(u+"code_verifier");if(!o)throw new Error("Missing code verifier.");const t={authorization_code:s,code_verifier:o};k.parse(t);const r=yield fetch(R(this.config.ssoBaseUrl,"/sso/access_token/exchange"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(t)});if(!r.ok)throw new Error(`ExchangeCode failed: ${r.statusText}`);const a=yield r.json(),l=E.parse(a);if(l.access_token)return localStorage.setItem(u+"access_token",l.access_token),l.access_token;throw new Error("Exchange failed")})}verifyAuth(){return g(this,null,function*(){const s=this.getAccessToken();if(!s)return!1;const o={access_token:s};B.parse(o);const t=yield fetch(R(this.config.ssoBaseUrl,"/sso/access_token/verify"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(!t.ok)return!1;const r=yield t.json(),a=T.parse(r);return a.access_token&&localStorage.setItem(u+"access_token",a.access_token),a.is_valid})}getAccessToken(){return localStorage.getItem(u+"access_token")}getAuthData(){const s=this.getAccessToken();if(!s)return null;const o=s.split(".");if(o.length!==3)return null;let t;try{const a=w(o[0]);t=JSON.parse(a)}catch(a){return null}if(t.alg!=="HS256"||t.typ!=="JWT")return null;let r;try{const a=JSON.parse(w(o[1]));r=C.parse(a)}catch(a){return null}return r}logout(){localStorage.removeItem(u+"access_token"),sessionStorage.removeItem(u+"code_verifier")}}const D=e.z.object({solana_address:e.z.string()}),O=e.z.object({deep_link:e.z.string(),polling_code:e.z.string(),expired_at:e.z.number()}),U=e.z.object({polling_code:e.z.string()}),Y=["pending","authorized","rejected","expired"],H=e.z.enum(Y),L=e.z.object({status:H,oracle_signature:e.z.optional(e.z.string()),oracle_public_key:e.z.optional(e.z.string()),solana_address:e.z.optional(e.z.string()),timestamp:e.z.optional(e.z.number()),session_address:e.z.optional(e.z.string())}),V=e.z.object({solana_address:e.z.string()}),N=e.z.object({session_address:e.z.string()});function Q(i){return c.PublicKey.findProgramAddressSync([Buffer.from("program_state")],i)}function Z(i){return c.PublicKey.findProgramAddressSync([Buffer.from("credential_signer")],i)}function v(i){return c.PublicKey.findProgramAddressSync([Buffer.from("session_registry")],i)}function M(i,s){return c.PublicKey.findProgramAddressSync([Buffer.from("session"),Buffer.from(i)],s)}function ee(i,s){return c.PublicKey.findProgramAddressSync([Buffer.from("solana"),i.toBuffer()],s)}function se(i,s,o,t){return c.PublicKey.findProgramAddressSync([Buffer.from("attestation"),i.toBuffer(),s.toBuffer(),o.toBuffer()],t)}const te="https://sso.alien.com",oe=5e3,re="9cstDz8WWRAFaq1vVpTjfHz6tjgh6SJaqYFeZWi1pFHG",ne="DeHa6pyZ2CFSbQQiNMm7FgoCXqmkX6tXG77C4Qycpta6",ae="22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",b=(i,s)=>new URL(s,i).toString(),q=e.z.object({ssoBaseUrl:e.z.url(),providerAddress:e.z.string(),pollingInterval:e.z.optional(e.z.number()),credentialSignerProgramId:e.z.optional(e.z.string()),sasProgramId:e.z.optional(e.z.string()),sessionRegistryProgramId:e.z.optional(e.z.string()),credentialAuthority:e.z.optional(e.z.string()),credentialName:e.z.optional(e.z.string()),schemaName:e.z.optional(e.z.string()),schemaVersion:e.z.optional(e.z.number())});class ie{constructor(s){this.config=q.parse(s),this.ssoBaseUrl=this.config.ssoBaseUrl||te,this.providerAddress=this.config.providerAddress,this.pollingInterval=this.config.pollingInterval||oe,this.credentialSignerProgramId=new c.PublicKey(this.config.credentialSignerProgramId||re),this.sasProgramId=new c.PublicKey(this.config.sasProgramId||ae),this.sessionRegistryProgramId=new c.PublicKey(this.config.sessionRegistryProgramId||ne)}generateDeeplink(s){return g(this,null,function*(){const o={solana_address:s};D.parse(o);const t=b(this.config.ssoBaseUrl,"/solana/link"),r=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(!r.ok)throw new Error(`GenerateLinkDeeplink failed: ${r.statusText}`);const a=yield r.json();return O.parse(a)})}pollAuth(s){return g(this,null,function*(){const o={polling_code:s};U.parse(o);const t=yield fetch(b(this.config.ssoBaseUrl,"/solana/poll"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(!t.ok)throw new Error(`Poll failed: ${t.statusText}`);const r=yield t.json();return L.parse(r)})}getAttestation(s){return g(this,null,function*(){const o={solana_address:s};V.parse(o);const t=yield fetch(b(this.config.ssoBaseUrl,"/solana/attestation"),{method:"POST",headers:{"Content-Type":"application/json","X-PROVIDER-ADDRESS":this.providerAddress},body:JSON.stringify(o)});if(t.status===404)return null;if(!t.ok)throw new Error(`GetAttestation failed: ${t.statusText}`);const r=yield t.json();return N.parse(r).session_address})}buildCreateAttestationTransaction(s){return g(this,null,function*(){const{connection:o,payerPublicKey:t,sessionAddress:r,oracleSignature:a,oraclePublicKey:l,timestamp:P,expiry:I}=s,[m]=Q(this.credentialSignerProgramId),y=yield o.getAccountInfo(m);if(!y)throw new Error("ProgramState account not found");const W=y.data,K=new c.PublicKey(W.slice(40,72)),J=new c.PublicKey(W.slice(72,104)),[ce]=Z(this.credentialSignerProgramId),[le]=v(this.sessionRegistryProgramId),[de]=M(r,this.sessionRegistryProgramId),[ge]=ee(t,this.sessionRegistryProgramId),[ue]=se(K,J,t,this.sasProgramId),G=Buffer.alloc(8);G.writeBigInt64LE(BigInt(P));const fe=Buffer.concat([Buffer.from(r),Buffer.from(t.toBase58()),G]),he=c.Ed25519Program.createInstructionWithPublicKey({publicKey:l.toBytes(),message:fe,signature:a}),Se=this.serializeCreateAttestationInstruction(r,Array.from(a),I,P),pe=new c.TransactionInstruction({keys:[{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:ce,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:K,isSigner:!1,isWritable:!1},{pubkey:J,isSigner:!1,isWritable:!1},{pubkey:ue,isSigner:!1,isWritable:!0},{pubkey:c.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:this.sasProgramId,isSigner:!1,isWritable:!1},{pubkey:c.SYSVAR_INSTRUCTIONS_PUBKEY,isSigner:!1,isWritable:!1},{pubkey:this.sessionRegistryProgramId,isSigner:!1,isWritable:!1},{pubkey:le,isSigner:!1,isWritable:!0},{pubkey:de,isSigner:!1,isWritable:!0},{pubkey:ge,isSigner:!1,isWritable:!0}],programId:this.credentialSignerProgramId,data:Se}),_=new c.Transaction;return _.add(he),_.add(pe),_})}serializeCreateAttestationInstruction(s,o,t,r){const a=Buffer.from([49,24,67,80,12,249,96,239]),l=Buffer.alloc(4);l.writeUInt32LE(s.length);const P=Buffer.from(s),I=Buffer.from(o),m=Buffer.alloc(8);m.writeBigInt64LE(BigInt(t));const y=Buffer.alloc(8);return y.writeBigInt64LE(BigInt(r)),Buffer.concat([a,l,P,I,m,y])}}n.AlienSolanaSsoClient=ie,n.AlienSolanaSsoClientSchema=q,n.AlienSsoClient=x,n.AlienSsoClientSchema=j,n.AuthorizeRequestSchema=S,n.AuthorizeResponseSchema=z,n.ExchangeCodeRequestSchema=k,n.ExchangeCodeResponseSchema=E,n.PollRequestSchema=A,n.PollResponseSchema=h,n.SolanaAttestationRequestSchema=V,n.SolanaAttestationResponseSchema=N,n.SolanaLinkRequestSchema=D,n.SolanaLinkResponseSchema=O,n.SolanaPollRequestSchema=U,n.SolanaPollResponseSchema=L,n.TokenInfoSchema=C,n.VerifyTokenRequestSchema=B,n.VerifyTokenResponseSchema=T,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,23 +1,27 @@
1
1
  {
2
2
  "name": "@alien_org/sso-sdk-core",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/alien-id/sso-sdk-js.git"
7
7
  },
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.esm.js",
10
+ "types": "./dist/index.d.ts",
8
11
  "exports": {
9
- ".": "./dist/index.js",
10
- "./*": "./dist/*.js"
11
- },
12
- "types": "./dist/types/index.d.ts",
13
- "typesVersions": {
14
- "*": {
15
- "*": ["dist/types/*.d.ts"]
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.esm.js",
15
+ "require": "./dist/index.cjs"
16
16
  }
17
17
  },
18
- "files": ["dist", "README.md"],
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
19
22
  "scripts": {
20
- "build": "tsc",
23
+ "build": "vite build",
24
+ "dev": "vite build --watch",
21
25
  "test": "jest",
22
26
  "test:unit": "jest tests/unit",
23
27
  "test:integration": "jest tests/integration",
@@ -26,7 +30,6 @@
26
30
  "prepublishOnly": "npm run build"
27
31
  },
28
32
  "devDependencies": {
29
- "@types/crypto-js": "^4.2.2",
30
33
  "@types/express": "^5.0.3",
31
34
  "@types/jest": "^30.0.0",
32
35
  "@types/node": "^24.3.0",
@@ -42,12 +45,15 @@
42
45
  "nock": "^14.0.10",
43
46
  "prettier": "^3.6.2",
44
47
  "ts-jest": "^29.4.1",
45
- "turbo": "^2.5.6"
48
+ "turbo": "^2.5.6",
49
+ "vite": "^7.1.12",
50
+ "vite-plugin-dts": "^4.5.4"
46
51
  },
47
52
  "dependencies": {
48
- "@noble/ed25519": "^3.0.0",
49
- "base64url": "^3.0.1",
50
- "crypto-js": "^4.2.0",
53
+ "js-sha256": "^0.11.1",
51
54
  "zod": "^4.1.5"
55
+ },
56
+ "peerDependencies": {
57
+ "@solana/web3.js": "^1.95.0"
52
58
  }
53
59
  }
package/dist/client.d.ts DELETED
@@ -1,28 +0,0 @@
1
- import { AuthorizeResponse, TokenInfo } from './schema';
2
- import { z } from 'zod/v4-mini';
3
- export interface JWTHeader {
4
- alg: string;
5
- typ: string;
6
- }
7
- export declare const AlienSsoSdkClientSchema: z.ZodMiniObject<{
8
- ssoBaseUrl: z.ZodMiniURL;
9
- providerAddress: z.ZodMiniString<string>;
10
- pollingInterval: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
11
- }, z.core.$strip>;
12
- export type AlienSsoSdkClientConfig = z.infer<typeof AlienSsoSdkClientSchema>;
13
- export declare class AlienSsoSdkClient {
14
- readonly config: AlienSsoSdkClientConfig;
15
- readonly pollingInterval: number;
16
- readonly ssoBaseUrl: string;
17
- readonly providerAddress: string;
18
- constructor(config: AlienSsoSdkClientConfig);
19
- private generateCodeVerifier;
20
- private generateCodeChallenge;
21
- getAuthDeeplink(): Promise<AuthorizeResponse>;
22
- pollAuth(pollingCode: string): Promise<string>;
23
- exchangeToken(authorizationCode: string): Promise<string>;
24
- verifyAuth(): Promise<boolean>;
25
- getAccessToken(): string | null;
26
- getAuthData(): TokenInfo | null;
27
- logout(): void;
28
- }
package/dist/client.js DELETED
@@ -1,185 +0,0 @@
1
- import { AuthorizeResponseSchema, ExchangeCodeRequestSchema, ExchangeCodeResponseSchema, AuthorizeRequestSchema, PollRequestSchema, PollResponseSchema, TokenInfoSchema, VerifyTokenRequestSchema, VerifyTokenResponseSchema, } from './schema';
2
- import { z } from 'zod/v4-mini';
3
- import base64url from 'base64url';
4
- import CryptoJS from 'crypto-js';
5
- import { joinUrl } from './utils';
6
- const SSO_BASE_URL = 'https://sso.alien.com';
7
- const POLLING_INTERVAL = 5000;
8
- const STORAGE_KEY = 'alien-sso_';
9
- export const AlienSsoSdkClientSchema = z.object({
10
- ssoBaseUrl: z.url(),
11
- providerAddress: z.string(),
12
- pollingInterval: z.optional(z.number()),
13
- });
14
- export class AlienSsoSdkClient {
15
- constructor(config) {
16
- this.config = AlienSsoSdkClientSchema.parse(config);
17
- this.ssoBaseUrl = this.config.ssoBaseUrl || SSO_BASE_URL;
18
- this.providerAddress = this.config.providerAddress;
19
- this.pollingInterval = this.config.pollingInterval || POLLING_INTERVAL;
20
- }
21
- generateCodeVerifier(length = 128) {
22
- let array;
23
- const cryptoObj = typeof window !== 'undefined' && window.crypto;
24
- if (cryptoObj && cryptoObj.getRandomValues) {
25
- array = new Uint8Array(length);
26
- cryptoObj.getRandomValues(array);
27
- }
28
- else {
29
- array = new Uint8Array(length);
30
- for (let i = 0; i < length; i++) {
31
- array[i] = Math.floor(Math.random() * 256);
32
- }
33
- }
34
- let str = '';
35
- for (let i = 0; i < array.length; i++) {
36
- str += String.fromCharCode(array[i]);
37
- }
38
- return base64url.encode(str);
39
- }
40
- async generateCodeChallenge(codeVerifier) {
41
- return CryptoJS.SHA256(codeVerifier).toString(CryptoJS.enc.Hex);
42
- }
43
- async getAuthDeeplink() {
44
- const codeVerifier = this.generateCodeVerifier();
45
- const codeChallenge = await this.generateCodeChallenge(codeVerifier);
46
- sessionStorage.setItem(STORAGE_KEY + 'code_verifier', codeVerifier);
47
- const authorizeUrl = `${this.config.ssoBaseUrl}/sso/authorize`;
48
- const authorizePayload = {
49
- code_challenge: codeChallenge,
50
- code_challenge_method: 'S256'
51
- };
52
- AuthorizeRequestSchema.parse(authorizePayload);
53
- const response = await fetch(authorizeUrl, {
54
- method: 'POST',
55
- headers: {
56
- 'Content-Type': 'application/json',
57
- 'X-PROVIDER-ADDRESS': this.providerAddress,
58
- },
59
- body: JSON.stringify(authorizePayload),
60
- });
61
- const json = await response.json();
62
- return AuthorizeResponseSchema.parse(json);
63
- }
64
- async pollAuth(pollingCode) {
65
- const pollPayload = {
66
- polling_code: pollingCode,
67
- };
68
- PollRequestSchema.parse(pollPayload);
69
- while (true) {
70
- const response = await fetch(joinUrl(this.config.ssoBaseUrl, '/sso/poll'), {
71
- method: 'POST',
72
- headers: {
73
- 'Content-Type': 'application/json',
74
- 'X-PROVIDER-ADDRESS': this.providerAddress,
75
- },
76
- body: JSON.stringify(pollPayload),
77
- });
78
- if (!response.ok) {
79
- throw new Error(`Poll failed: ${response.statusText}`);
80
- }
81
- const json = await response.json();
82
- const pollResponse = PollResponseSchema.parse(json);
83
- if (pollResponse.status === 'authorized' &&
84
- pollResponse.authorization_code) {
85
- return pollResponse.authorization_code;
86
- }
87
- if (pollResponse.status === 'pending') {
88
- await new Promise((resolve) => setTimeout(resolve, this.pollingInterval));
89
- }
90
- else {
91
- throw new Error(`Poll failed`);
92
- }
93
- }
94
- }
95
- async exchangeToken(authorizationCode) {
96
- const codeVerifier = sessionStorage.getItem(STORAGE_KEY + 'code_verifier');
97
- if (!codeVerifier)
98
- throw new Error('Missing code verifier.');
99
- const exchangeCodePayload = {
100
- authorization_code: authorizationCode,
101
- code_verifier: codeVerifier,
102
- };
103
- ExchangeCodeRequestSchema.parse(exchangeCodePayload);
104
- const response = await fetch(joinUrl(this.config.ssoBaseUrl, '/sso/access_token/exchange'), {
105
- method: 'POST',
106
- headers: {
107
- 'Content-Type': 'application/json',
108
- 'X-PROVIDER-ADDRESS': this.providerAddress,
109
- },
110
- body: JSON.stringify(exchangeCodePayload),
111
- });
112
- if (!response.ok) {
113
- throw new Error(`ExchangeCode failed: ${response.statusText}`);
114
- }
115
- const json = await response.json();
116
- const exchangeCodeResponse = ExchangeCodeResponseSchema.parse(json);
117
- if (exchangeCodeResponse.access_token) {
118
- localStorage.setItem(STORAGE_KEY + 'access_token', exchangeCodeResponse.access_token);
119
- return exchangeCodeResponse.access_token;
120
- }
121
- else {
122
- throw new Error('Exchange failed');
123
- }
124
- }
125
- async verifyAuth() {
126
- const access_token = this.getAccessToken();
127
- if (!access_token) {
128
- throw new Error('Access token is invalid.');
129
- }
130
- const verifyTokenPayload = {
131
- access_token,
132
- };
133
- VerifyTokenRequestSchema.parse(verifyTokenPayload);
134
- const response = await fetch(joinUrl(this.config.ssoBaseUrl, '/sso/access_token/verify'), {
135
- method: 'POST',
136
- headers: {
137
- 'Content-Type': 'application/json',
138
- 'X-PROVIDER-ADDRESS': this.providerAddress,
139
- },
140
- body: JSON.stringify(verifyTokenPayload),
141
- });
142
- if (!response.ok) {
143
- throw new Error(`VerifyToken failed: ${response.statusText}`);
144
- }
145
- const json = await response.json();
146
- const verifyTokenResponse = VerifyTokenResponseSchema.parse(json);
147
- return verifyTokenResponse.is_valid;
148
- }
149
- getAccessToken() {
150
- return localStorage.getItem(STORAGE_KEY + 'access_token');
151
- }
152
- getAuthData() {
153
- const token = this.getAccessToken();
154
- if (!token)
155
- return null;
156
- const tokenParts = token.split('.');
157
- if (tokenParts.length !== 3) {
158
- return null;
159
- }
160
- let header;
161
- try {
162
- const headerJson = base64url.decode(tokenParts[0]);
163
- header = JSON.parse(headerJson);
164
- }
165
- catch {
166
- return null;
167
- }
168
- if (header.alg !== 'HS256' || header.typ !== 'JWT') {
169
- return null;
170
- }
171
- let payload;
172
- try {
173
- const payloadJson = JSON.parse(base64url.decode(tokenParts[1]));
174
- payload = TokenInfoSchema.parse(payloadJson);
175
- }
176
- catch {
177
- return null;
178
- }
179
- return payload;
180
- }
181
- logout() {
182
- localStorage.removeItem(STORAGE_KEY + 'access_token');
183
- sessionStorage.removeItem(STORAGE_KEY + 'code_verifier');
184
- }
185
- }
package/dist/errors.d.ts DELETED
@@ -1,8 +0,0 @@
1
- declare class BaseError extends Error {
2
- constructor(message: string);
3
- }
4
- export declare class ValidationError extends BaseError {
5
- }
6
- export declare class AuthenticationError extends BaseError {
7
- }
8
- export {};
package/dist/errors.js DELETED
@@ -1,13 +0,0 @@
1
- class BaseError extends Error {
2
- constructor(message) {
3
- super(message);
4
- this.name = this.constructor.name;
5
- if (Error.captureStackTrace) {
6
- Error.captureStackTrace(this, this.constructor);
7
- }
8
- }
9
- }
10
- export class ValidationError extends BaseError {
11
- }
12
- export class AuthenticationError extends BaseError {
13
- }
package/dist/index.js DELETED
@@ -1,3 +0,0 @@
1
- export * from './client';
2
- export * from './errors';
3
- export * from './schema';
package/dist/schema.d.ts DELETED
@@ -1,62 +0,0 @@
1
- import { z } from 'zod/v4-mini';
2
- /**
3
- * Authorize request/response schema
4
- */
5
- export declare const AuthorizeRequestSchema: z.ZodMiniObject<{
6
- code_challenge: z.ZodMiniString<string>;
7
- code_challenge_method: z.ZodMiniLiteral<"S256">;
8
- }, z.core.$strip>;
9
- export type AuthorizeRequest = z.infer<typeof AuthorizeRequestSchema>;
10
- export declare const AuthorizeResponseSchema: z.ZodMiniObject<{
11
- deep_link: z.ZodMiniString<string>;
12
- polling_code: z.ZodMiniString<string>;
13
- expired_at: z.ZodMiniNumber<number>;
14
- }, z.core.$strip>;
15
- export type AuthorizeResponse = z.infer<typeof AuthorizeResponseSchema>;
16
- /**
17
- * Poll request/response schema
18
- */
19
- export declare const PollRequestSchema: z.ZodMiniObject<{
20
- polling_code: z.ZodMiniString<string>;
21
- }, z.core.$strip>;
22
- export type PollRequest = z.infer<typeof PollRequestSchema>;
23
- export declare const PollResponseSchema: z.ZodMiniObject<{
24
- status: z.ZodMiniEnum<{
25
- pending: "pending";
26
- authorized: "authorized";
27
- }>;
28
- authorization_code: z.ZodMiniOptional<z.ZodMiniString<string>>;
29
- }, z.core.$strip>;
30
- export type PollResponse = z.infer<typeof PollResponseSchema>;
31
- /**
32
- * ExchangeCode request/response schema
33
- */
34
- export declare const ExchangeCodeRequestSchema: z.ZodMiniObject<{
35
- authorization_code: z.ZodMiniString<string>;
36
- code_verifier: z.ZodMiniString<string>;
37
- }, z.core.$strip>;
38
- export type ExchangeCodeRequest = z.infer<typeof ExchangeCodeRequestSchema>;
39
- export declare const ExchangeCodeResponseSchema: z.ZodMiniObject<{
40
- access_token: z.ZodMiniString<string>;
41
- }, z.core.$strip>;
42
- export type ExchangeCodeResponse = z.infer<typeof ExchangeCodeResponseSchema>;
43
- /**
44
- * VerifyToken request/response schema
45
- */
46
- export declare const VerifyTokenRequestSchema: z.ZodMiniObject<{
47
- access_token: z.ZodMiniString<string>;
48
- }, z.core.$strip>;
49
- export type VerifyTokenRequest = z.infer<typeof VerifyTokenRequestSchema>;
50
- export declare const VerifyTokenResponseSchema: z.ZodMiniObject<{
51
- is_valid: z.ZodMiniBoolean<boolean>;
52
- }, z.core.$strip>;
53
- export type VerifyTokenResponse = z.infer<typeof VerifyTokenResponseSchema>;
54
- /**
55
- * Token info schema
56
- */
57
- export declare const TokenInfoSchema: z.ZodMiniObject<{
58
- app_callback_session_address: z.ZodMiniString<string>;
59
- expired_at: z.ZodMiniNumber<number>;
60
- issued_at: z.ZodMiniNumber<number>;
61
- }, z.core.$strip>;
62
- export type TokenInfo = z.infer<typeof TokenInfoSchema>;
package/dist/schema.js DELETED
@@ -1,52 +0,0 @@
1
- import { z } from 'zod/v4-mini';
2
- /**
3
- * Authorize request/response schema
4
- */
5
- export const AuthorizeRequestSchema = z.object({
6
- code_challenge: z.string(),
7
- code_challenge_method: z.literal('S256'),
8
- });
9
- export const AuthorizeResponseSchema = z.object({
10
- deep_link: z.string(),
11
- polling_code: z.string(),
12
- expired_at: z.number(),
13
- });
14
- /**
15
- * Poll request/response schema
16
- */
17
- export const PollRequestSchema = z.object({
18
- polling_code: z.string(),
19
- });
20
- const status = ['pending', 'authorized'];
21
- const StatusEnum = z.enum(status);
22
- export const PollResponseSchema = z.object({
23
- status: StatusEnum,
24
- authorization_code: z.optional(z.string()),
25
- });
26
- /**
27
- * ExchangeCode request/response schema
28
- */
29
- export const ExchangeCodeRequestSchema = z.object({
30
- authorization_code: z.string(),
31
- code_verifier: z.string(),
32
- });
33
- export const ExchangeCodeResponseSchema = z.object({
34
- access_token: z.string(),
35
- });
36
- /**
37
- * VerifyToken request/response schema
38
- */
39
- export const VerifyTokenRequestSchema = z.object({
40
- access_token: z.string(),
41
- });
42
- export const VerifyTokenResponseSchema = z.object({
43
- is_valid: z.boolean(),
44
- });
45
- /**
46
- * Token info schema
47
- */
48
- export const TokenInfoSchema = z.object({
49
- app_callback_session_address: z.string(),
50
- expired_at: z.number(),
51
- issued_at: z.number(),
52
- });
package/dist/server.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { AuthorizeResponse } from './schema';
2
- import { z } from 'zod/v4-mini';
3
- export declare const AlienSsoSdkServerConfigSchema: z.ZodMiniObject<{
4
- providerAddress: z.ZodMiniString<string>;
5
- providerPrivateKey: z.ZodMiniString<string>;
6
- ssoBaseUrl: z.ZodMiniURL;
7
- }, z.core.$strip>;
8
- export type AlienSsoSdkServerConfig = z.infer<typeof AlienSsoSdkServerConfigSchema>;
9
- export declare class AlienSsoSdkServer {
10
- readonly config: AlienSsoSdkServerConfig;
11
- readonly ssoBaseUrl: string;
12
- constructor(config: AlienSsoSdkServerConfig);
13
- authorize(codeChallenge: string): Promise<AuthorizeResponse | null>;
14
- }
package/dist/server.js DELETED
@@ -1,59 +0,0 @@
1
- import { AuthorizeResponseSchema, AuthorizeRequestSchema, } from './schema';
2
- import { z } from 'zod/v4-mini';
3
- import { signAsync } from '@noble/ed25519';
4
- import { AuthenticationError, ValidationError } from './errors';
5
- import { joinUrl } from './utils';
6
- const DEFAULT_SSO_BASE_URL = 'https://sso.alien-api.com';
7
- export const AlienSsoSdkServerConfigSchema = z.object({
8
- providerAddress: z.string(),
9
- providerPrivateKey: z.string(),
10
- ssoBaseUrl: z.url(),
11
- });
12
- export class AlienSsoSdkServer {
13
- constructor(config) {
14
- const parsedConfig = AlienSsoSdkServerConfigSchema.parse(config);
15
- this.config = parsedConfig;
16
- this.ssoBaseUrl = parsedConfig.ssoBaseUrl || DEFAULT_SSO_BASE_URL;
17
- }
18
- async authorize(codeChallenge) {
19
- if (!codeChallenge || codeChallenge.length !== 64) {
20
- throw new ValidationError('Invalid code challenge');
21
- }
22
- // Note: order of fields important!
23
- const signaturePayload = {
24
- provider_address: this.config.providerAddress,
25
- code_challenge: codeChallenge,
26
- code_challenge_method: 'S256',
27
- };
28
- const message = JSON.stringify(signaturePayload);
29
- const messageBytes = new TextEncoder().encode(message);
30
- const privateKeyBytes = Buffer.from(this.config.providerPrivateKey, 'hex');
31
- const signature = await signAsync(messageBytes, privateKeyBytes);
32
- const authorizePayload = {
33
- ...signaturePayload,
34
- provider_signature: Buffer.from(signature).toString('hex'),
35
- };
36
- AuthorizeRequestSchema.parse(authorizePayload);
37
- const response = await fetch(joinUrl(this.config.ssoBaseUrl, '/authorize'), {
38
- method: 'POST',
39
- headers: {
40
- 'Content-Type': 'application/json',
41
- },
42
- body: JSON.stringify(authorizePayload),
43
- });
44
- if (!response.ok) {
45
- throw new AuthenticationError(`SSO Router Authorization failed: ${response.status} ${response.statusText} ${await response.text()}`);
46
- }
47
- const json = await response.json();
48
- const { deep_link, polling_code, expired_at } = AuthorizeResponseSchema.parse(json);
49
- const deepLinkBytes = Buffer.from(deep_link, 'utf8');
50
- const deepLinkSignature = await signAsync(deepLinkBytes, privateKeyBytes);
51
- const deepLinkUrl = new URL(deep_link);
52
- deepLinkUrl.searchParams.set('link_signature', Buffer.from(deepLinkSignature).toString('hex'));
53
- return {
54
- deep_link: deepLinkUrl.toString(),
55
- polling_code,
56
- expired_at,
57
- };
58
- }
59
- }
package/dist/utils.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const joinUrl: (base: string, path: string) => string;
package/dist/utils.js DELETED
@@ -1,3 +0,0 @@
1
- export const joinUrl = (base, path) => {
2
- return new URL(path, base).toString();
3
- };