 			res.send r
 			next()
 
+clientCallback = (data, res, next) -> (e, r) -> #data:state,provider,redirect_uri,origin
+	body = formatters.build e || r
+	body.state = data.state if data.state
+	body.provider = data.provider.toLowerCase() if data.provider
+	view = '<script>(function() {\n'
+	view += '\t"use strict";\n'
+	view += '\tvar msg=' + JSON.stringify(JSON.stringify(body)) + ';\n'
+	if data.redirect_uri
+		view += '\tdocument.location.href = "' + data.redirect_uri + '#oauthio=" + encodeURIComponent(msg);\n'
+	else
+		view += '\tvar opener = window.opener || window.parent.window.opener;\n'
+		view += '\tif (opener)\n'
+		view += '\t\topener.postMessage(msg, "' + data.origin + '");\n'
+		view += '\twindow.close();\n'
+	view += '})();</script>'
+	res.send view
+	next()
+
 # oauth: handle callbacks
 server.get config.base + '/', (req, res, next) ->
 	if Object.keys(req.params).length == 0

		return next new check.Error 'state', 'must be present'
	db.states.get req.params.state, (err, state) ->
		return next err if err
		return next new check.Error 'state', 'invalid or expired' if not state || state.step != "0"
		oauth[state.oauthv].access_token state, req, (e, r) ->
			status = if e then 'error' else 'success'


					r.code = req.params.state
				if state.options.response_type == 'token'
					db.states.del req.params.state, (->)
			callback e, r

# oauth: popup or redirection to provider's authorization url
server.get config.base + '/auth/:provider', (req, res, next) ->
	res.setHeader 'Content-Type', 'text/html'

	domain = null
	origin = null
	ref = fixUrl(req.headers['referer'] || req.headers['origin'] || req.params.d || req.params.redirect_uri || "")
	urlinfos = Url.parse ref
	if not urlinfos.hostname
		return next new restify.InvalidHeaderError 'Missing origin or referer.'
	origin = urlinfos.protocol + '//' + urlinfos.host

	options = {}
	if req.params.opts
		try
			options = JSON.parse(req.params.opts)
			return cb new check.Error 'Options must be an object' if typeof options != 'object'
		catch e
			return cb new check.Error 'Error in request parameters'

	callback = clientCallback state:options.state, provider:req.params.provider, origin:origin, redirect_uri:req.params.redirect_uri, res, next

	key = req.params.k
	if not key
		return callback new restify.MissingParameterError 'Missing OAuthd public key.'

	oauthv = req.params.oauthv && {
		"2":"oauth2"
